【问题标题】:Throwout an error "not JSON serializable" when trying to write a json file尝试编写 json 文件时抛出错误“不可 JSON 序列化”
【发布时间】:2016-08-26 02:35:00
【问题描述】:

我正在尝试重现像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: &lt;open file 'test.json', mode 'w' at 0x1032c66f0&gt; is not JSON serializable

请帮帮我,谢谢~

【问题讨论】:

  • json.dumps 这是转储到字符串(注意s),您想要正常的json.dump 转储到文件。
  • @BurhanKhalid 谢谢,我需要更精确地处理 python!

标签: json python-2.7 serialization


【解决方案1】:

在示例代码中

with open('test.json','w') as f:
    json.dump(f,z)

你应该用z交换f,函数的参数是(对象,输出文件)。

【讨论】:

  • 我的粗心,我在第一个代码中使用了 dumps() 而不是 dump() 并且我发现没有任何东西被转储到 dictTree.json 文件中,所以我只是改变了两个争论的位置。谢谢你!!!!!!!
猜你喜欢
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 1970-01-01
  • 2012-02-16
  • 1970-01-01
  • 2016-04-20
相关资源
最近更新 更多