我有3 * 10維的np數組,每列都是其x,y,z座標的頂點。在Python中將數據寫入json
我想將這些數據輸出到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
而且當我打開保存在Chrome JSON文件,它看起來醜陋這樣,
"{\n\"v\"0 : {\n\"x\" : 0.0184074,\n\"y\" : 0.354329,\n\"z\" : -0.024123\n}" #and so on ...
我做錯了什麼?
不要在旅途中解決您的代碼,它會迷惑人的樣子在未來的問題 –