无法在python中使用json.dumps将Dictionary转换为JSON对象

问题描述

我正在尝试使用json.dumps()

转换字典
def create_custom(json_input):
    custom = dict()
    custom['list'] = dict()
    custom['list']['Elements'] = json_input['nodes']
    custom['list']['links'] = json_input['links']
    return custom

JsonData = create_custom(json_graph.node_link_data(G))

for i,j in enumerate(Elements):
    JsonData['list']['Elements'][i]['Shape'] = j['Shape']

上面的代码还不完整,但是我得到的最终输出是字典

输出

{'list': {'Elements': [{'text': 'Task 1','Shape': 'Decision','id': 0},{'text': 'Task 2','id': 1},{'text': 'Task 3','id': 2},{'text': 'Task 4','id': 3},{'text': 'Task 5','Shape': 'Rectangle','id': 4},{'text': 'Task 6','id': 5}],'links': [{'source': 0,'target': 1,'key': 0},{'source': 0,'target': 4,{'source': 1,'target': 2,'target': 3,{'source': 2,{'source': 3,{'source': 4,'target': 5,{'source': 5,'key': 0}]}}

当我将上述输出转换为JSON对象时

json.dumps(JsonData)

我遇到错误

~\AppData\Local\Continuum\anaconda3\lib\json\encoder.py in default(self,o)
    177 
    178         """
--> 179         raise TypeError(f'Object of type {o.__class__.__name__} '
    180                         f'is not JSON serializable')
    181 

TypeError: Object of type int64 is not JSON serializable

我遇到了很多答案,但他们都在谈论numpy array等。

我要去哪里了

解决方法

我无法重新创建错误,但是json.dumps对我来说很好。请参考以下屏幕截图:

Code sample and output

我尝试的代码:

import json
JsonData={'list': {'Elements': [{'text': 'Task 1','Shape': 'Decision','id': 0},{'text': 'Task 2','id': 1},{'text': 'Task 3','id': 2},{'text': 'Task 4','id': 3},{'text': 'Task 5','Shape': 'Rectangle','id': 4},{'text': 'Task 6','id': 5}],'links': [{'source': 0,'target': 1,'key': 0},{'source': 0,'target': 4,{'source': 1,'target': 2,'target': 3,{'source': 2,{'source': 3,{'source': 4,'target': 5,{'source': 5,'key': 0}]}}
print(type(JsonData))
print(json.dumps(JsonData))
print(type(json.dumps(JsonData)))