Search:

Search all manuals
Search this manual
Manual
Couchbase Client Library: Python 1.0
Community Wiki and Resources
Download Client Library
Python Client Library
SDK Forum
Additional Resources
Community Wiki
Community Forums
Couchbase SDKs
Parent Section
1.3 Try it Out!
Chapter Sections
Chapters

1.3.5. Storing JSON Documents

While storing and retreiving JSON strings is a straightforward process, documents in a typical application are likely at some point to be represented by domain objects or some data structure other than a string. For example, the beer documents could be represented by an instance of a Beer class in memory or more simply as dictionaries. The Python Client Library will accept arbitrary strings as values. However, on the server, these strings (if not JSON) will be stored as binary attachments to a JSON document. The impact of being an attachment is that it will not be indexed in a view. A better solution then, is to serialize data objects or dictionaries to JSON strings before storing them and deserializing the JSON document strings to objects or dictionaries when retrieving them.

Instead of the JSON string above, using a dictionary provides an easy way to organize documents.

newBeer = \
{
   "name": "Old Yankee Ale",
   "abv": 5.00,
   "ibu": 0,
   "srm": 0,
   "upc": 0,
   "type": "beer",
   "brewery_id": "110a45622a",
   "updated": "2012-08-30 20:00:20",
   "description": ".A medium-bodied Amber Ale",
   "style": "American-Style Amber",
   "category": "North American Ale"
}

To store this dictionary as a JSON document, simply use the dumps method of the json module.

import json
bucket.set(key, 0, 0, json.dumps(newBeer)

To retrieve the stored document string into a dictionary instance, use the json loads method.

savedBeer = json.loads(bucket.get(key)[2])
print savedBeer["name"]