Writing JSON documents to Couchbase

When you are dealing with larger and more complex JSON documents with Couchbase Server, you can use a JSON library to handle and convert the JSON.

Note that some Couchbase SDKs provides JSON conversions as part of the method call; with these SDKs you do not need to explicitly load a JSON conversion library and do a conversion prior to reading and writing a JSON document. For more information, please consult the Language Reference for your chosen SDK.

Tip: If you are currently using serialized objects with memcached or Membase, you can continue using this in Couchbase Server 1.8+. JSON offers the advantage of providing heterogeneous platform support, and will enable you to use new features of Couchbase Server such as view, querying and indexing.

The following illustrates a simple JSON document used to represent a beer. For JSON, string-value pairs are the basic building blocks you use to represent information:

{
    "abv": 10.0,
    "brewery": "Legacy Brewing Co.",
    "category": "North American Ale",
    "name": "Hoptimus Prime",
    "style": "Imperial or Double India Pale Ale",
    "updated": [2010, 7, 22, 20, 0, 20],
    "available": true
}

The unique identifier we provide within the JSON is beer_Hoptimus_Prime. Notice there are a variety of valid values that can be used within the JSON document to represent your real-world item: floats, strings, arrays, and Booleans are used in this case to represent beer number, category, update time, and availability. The JSON document is itself a hash delimited by curly brackets, {}, with commas to separate each string-value pair. Collectively, all string-value pairs in a block are called members.

To save a JSON document into Couchbase Server, you would provide the JSON-encoded document as a parameter to your store method:

<?php
// create connection to Couchbase
// defaults to the “default” bucket

$cb = new Couchbase("localhost:8091");

// create very simple brew

$mybrew = array(“name” => “Good Beer”, “brewery” => "The Kitchen");

$cb->set("beer_My_Brew", json_encode($mybrew));
?>

In the example above we create an array $mybrew to represent our beer with two attributes, the beer name and the brewery. We then store the beer as a valid JSON document by using json_encode() and passing in the result as the value to set(). When we store the JSON document, we specify the key ‘beer_My_Brew.’

In the presidents example provided in the section on Performing a bulk set, we used one of the many JSON libraries available that convert JSON documents into native objects. In this case we use Gson, an open source library which converts JSON documents into Java:

Gson gson = new Gson();

President[] Presidents = gson.fromJson(new FileReader("Presidents.json"), President[].class);

for (President entry : Presidents) {
    String JSONentry = gson.toJson(entry);
    c.set(entry.presidency, 1200, JSONentry);
}