claudia
claudia

Reputation: 87

How do I load JSON into Couchbase Headless Server in Python?

I am trying to create a Python script that can take a JSON object and insert it into a headless Couchbase server. I have been able to successfully connect to the server and insert some data. I'd like to be able to specify the path of a JSON object and upsert that.

So far I have this:

from couchbase.bucket import Bucket
from couchbase.exceptions import CouchbaseError
import json

cb = Bucket('couchbase://XXX.XXX.XXX?password=XXXX')
print cb.server_nodes

#tempJson = json.loads(open("myData.json","r"))

try:
       result = cb.upsert('healthRec', {'record': 'bob'})
#      result = cb.upsert('healthRec', {'record': tempJson})

except CouchbaseError as e:
        print "Couldn't upsert", e
        raise

print(cb.get('healthRec').value)

I know that the first commented out line that loads the json is incorrect because it is expecting a string not an actual json... Can anyone help?

Thanks!

Upvotes: 0

Views: 488

Answers (2)

Matt Carabine
Matt Carabine

Reputation: 68

I know that you've found a solution that works for you in this instance but I thought I'd correct the issue that you experienced in your initial code snippet.

json.loads() takes a string as an input and decodes the json string into a dictionary (or whatever custom object you use based on the object_hook), which is why you were seeing the issue as you are passing it a file handle. There is actually a method json.load() which works as expected, as you have used in your eventual answer.

You would have been able to use it as follows (if you wanted something slightly less verbose than the with statement): tempJson = json.load(open("myData.json","r"))

As Kirk mentioned though if you have a large number of json documents to insert then it might be worth taking a look at cbdocloader as it will handle all of this boilerplate code for you (with appropriate error handling and other functionality). This readme covers the uses of cbdocloader and how to format your data correctly to allow it to load your documents into Couchbase Server.

Upvotes: 0

claudia
claudia

Reputation: 87

Figured it out:

with open('myData.json', 'r') as f:
        data = json.load(f)

try:
        result = cb.upsert('healthRec', {'record': data})

I am looking into using cbdocloader, but this was my first step getting this to work. Thanks!

Upvotes: 1

Related Questions