'Throwout an error "not JSON serializable" when trying to write a json file

I'm trying to reproduce a json file like the flare.json, and the names I have are like the IndicatorCode, so I'm trying to build a dictTree and reproduce the json file mentioned above, and my code goes here:

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)

and the error is like this:

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

To simplify my question, I just reproduce the error like follow using the simplified output data:

>>> z = {'name': 'indicator', 'children': [{'name': '1','size':1}, {'name':2,"size" :2}]}
>>> with open('test.json','w') as f:
...     json.dump(f,z)

Then I get the same error:TypeError: <open file 'test.json', mode 'w' at 0x1032c66f0> is not JSON serializable

Please help me, thx~



Solution 1:[1]

In the example code

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

you should exchange f with z, arguments of the function are (object, output file).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user2314737