2016-06-30 35 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コードはそれは、私はクロームで保存したJSONファイルを開いたときにまた、それは、このような醜い次のエラーに

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

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 

を与える

#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 

です

私は何が間違っていますか?

+0

は、外出先であなたのコードを修正しない、それは誰もどのようにルックスを混乱させます将来の質問で –

答えて

0

例外が発生しますが、引数としてJSON文字列ではないファイル名を期待json.loadsを、使用しているため。

しかし、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として辞書::

引数としてファイルオブジェクトと

使用json.load

with open("text.json", "w") as outfile: 
    json.dump(data, outfile, indent=4) 
、代わりの json.loads

代わりに文字列を構築する、辞書を構築ファイル名

あなたが適切に最初にあなたのJSONを構築する必要が
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

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) 
関連する問題