用python将数据写入json

用python将数据写入json,python,json,numpy,dictionary,Python,Json,Numpy,Dictionary,我有一个3*10维的np数组,每一列都是顶点和它的x,y,z坐标 我想将这些数据输出到JSON文件,如下所示 { "v0" : { "x" : 0.0184074, "y" : 0.354329, "z" : -0.024123 }, "v1" : { "x" : 0.34662, "y" : 0.338337, "z" : -0.0333459 } #and so on... 这是我的python代码 #vertices is np array of 3*10 dimention for x

我有一个3*10维的np数组,每一列都是顶点和它的x,y,z坐标

我想将这些数据输出到JSON文件,如下所示

{
"v0" : {
"x" : 0.0184074,
"y" : 0.354329,
"z" : -0.024123
},
"v1" : {
"x" : 0.34662,
"y" : 0.338337,
"z" : -0.0333459
}
#and so on...
这是我的python代码

#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
它给出了以下错误

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

我做错了什么?

您应该调用
json.load(fileObj)
,这里我修改了:

#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'))

引发此异常的原因是您使用了
json.loads
,它需要一个json字符串作为参数,而不是文件名

with open('text.json', 'r') as infile:
    r = json.load(infile)
但是,转储JSON的方式也是错误的。您正在生成一个字符串
s
,其中包含无效的JSON。然后,您将使用
json.dump
转储这个字符串

构建字典而不是构建字符串:

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]), 
}
将该字典作为JSON转储到文件:

with open("text.json", "w") as outfile:
    json.dump(data, outfile, indent=4)
使用文件对象作为参数的
json.load
,而不是使用文件名的
json.load

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

您需要首先正确构造json:

s = {}
for x in xrange(0,10):
    s["v"+str(x)]= { "x":str(vertices[0][x]),"y":str(vertices[1][x]),"z":str(vertices[2][x]) }
然后你把它扔了:

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

不要在运行中修改代码,这会让任何人对将来的问题感到困惑