我正在尝试重现像flare.json这样的json文件,我的名字就像IndicatorCode,所以我正在尝试构建一个dictTree并重现上面提到的json文件,我的代码在这里:
import numpy as np
import pandas as pd
import json
li = [];
dictTree = {}
out = {"name":'Indicators', 'children':[]};
dic = pd.read_csv('../dictTree.csv')
dicta = {}
for i in range(len(dic)):
dicta[dic["IndicatorCode"][i]] = dic["IndicatorName"][i];
li.append(dic["IndicatorCode"][i])
for x in li:
i = 0
k = 0
d = dictTree
while k < 2:
s = ''
while x[i] != '.':
s += x[i]
i = i+1
i=i+1
k= k+1
if s not in d:
d[s] = {}
#print s
d = d[s]
s = ''
while i < len(x) and x[i] != '.':
s += x[i]
i = i+1
if s not in d:
d[s] = []
d[s].append({'Name':x,"info":dicta[x]})
level1 = out['children']
for x in dictTree:
level2 = []
level1.append({"name":x,"children":level2})
dictlevel2 = dictTree[x]
for y in dictlevel2:
level3 = []
level2.append({'name':y,'children':level3})
dictlevel3 = dictlevel2[y]
for z in dictlevel3:
level3.append({'name':z,'children':dictlevel3[z]})
with open('dictTree.json','w') as f:
json.dumps(f,out)
,错误是这样的:
Traceback (most recent call last):
File "produceTreeJson.py", line 46, in <module>
json.dumps(f,out)
File "/Users/Peter/anaconda/lib/python2.7/json/__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "/Users/Peter/anaconda/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Users/Peter/anaconda/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
File "/Users/Peter/anaconda/lib/python2.7/json/encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <open file 'dictTree.json', mode 'w' at 0x107b43030> is not JSON serializable
为了简化我的问题,我只是使用简化的输出数据重现错误:
>>> z = {'name': 'indicator', 'children': [{'name': '1','size':1}, {'name':2,"size" :2}]}
>>> with open('test.json','w') as f:
... json.dump(f,z)
然后我收到同样的错误:TypeError: <open file 'test.json', mode 'w' at 0x1032c66f0> is not JSON serializable
请帮帮我,谢谢〜
答案 0 :(得分:0)
在示例代码中
with open('test.json','w') as f:
json.dump(f,z)
你应该用f
交换z
,函数的参数是(对象,输出文件)。