在python中将数据写入json

时间:2016-06-30 07:54:31

标签: python json numpy dictionary

我有3 * 10维的np数组,每列都是顶点,其x,y,z坐标。

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

StringBuilder error = new StringBuilder();
int returnValue = my_func(error);

这是我的python代码

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

它出现以下错误

#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

此外,当我在chrome中打开已保存的json文件时,它看起来很难看,

    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

我做错了什么?

3 个答案:

答案 0 :(得分:0)

你应该致电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'))

答案 1 :(得分:0)

引发异常是因为您使用json.loads,它期望JSON字符串作为参数而不是文件名。

但是,转储JSON的方式也是错误的。您正在构建一个包含无效JSON的字符串s。然后,您将使用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.loads的文件名。

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

答案 2 :(得分:0)

你需要先正确构建你的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)