Mohan Mohan - 1 year ago 37
JSON Question

Writing data to json in python

I have np array of 3*10 dimension, each column is vertex with its x, y, z co-ordinate.

I want to output this data to JSON file like following.

"v0" : {
"x" : 0.0184074,
"y" : 0.354329,
"z" : -0.024123
"v1" : {
"x" : 0.34662,
"y" : 0.338337,
"z" : -0.0333459
#and so on...

Here is my python code

#vertices is np array of 3*10 dimention
for x in xrange(0,10):
s += "\n\"v\""+ str(x) +" : {";
s += "\n\"x\" : "+str(vertices[0][x]) +","
s += "\n\"y\" : "+str(vertices[1][x]) +","
s += "\n\"z\" : "+str(vertices[2][x])
s += "\n},"
s += "\n}"

with open("text.json", "w") as outfile:
json.dump(s, outfile, indent=4)
r = json.load(open('text.json', 'r')) #this line updated, fixed wrong syntax

It gives following error

Traceback (most recent call last):
File "", line 32, in <module>
r = json.loads("text.json");
File "/usr/lib/python2.7/json/", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

Further when I open saved json file in chrome it looks ugly like this,

"{\n\"v\"0 : {\n\"x\" : 0.0184074,\n\"y\" : 0.354329,\n\"z\" : -0.024123\n}" #and so on ...

What am I doing wrong?

Answer Source

The exception is raised because you use json.loads, which expects a JSON string as argument not a filename.

However, the way you dump the JSON is wrong too. You are building a string s, which contains invalid JSON. Then, you are dumping this single string with json.dump.

Instead of building a string, build a dictionary:

data = {}
for x in xrange(0,10):
    data["v" + str(x)] = {
        "x": str(vertices[0][x]),
        "y": str(vertices[1][x]),
        "z": str(vertices[2][x]), 

Dump that dictionary:

with open("text.json", "w") as outfile:
    json.dump(data, outfile, indent=4)

Use json.load with a file object as argument, instead of json.loads with the filename.

with open('text.json', r) as infile:
    r = json.load(infile)