2016-06-30 57 views
-1

我有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 ... 

我做錯了什麼?

+0

不要在旅途中解決您的代碼,它會迷惑人的樣子在未來的問題 –

回答

0

將引發異常,因爲您使用json.loads,這需要一個JSON字符串作爲參數不是文件名。

但是,您轉儲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.loads與文件名。

with open('text.json', 'r') as infile: 
    r = json.load(infile) 
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')) 
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)