为了账号安全,请及时绑定邮箱和手机立即绑定

无法在 python 中使用 json.dumps() 将字典转换为 JSON 对象

无法在 python 中使用 json.dumps() 将字典转换为 JSON 对象

慕虎7371278 2023-05-16 15:08:35
我正在尝试使用转换字典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 customJsonData = 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', 'Shape': 'Decision', 'id': 1},   {'text': 'Task 3', 'Shape': 'Decision', 'id': 2},   {'text': 'Task 4', 'Shape': 'Decision', 'id': 3},   {'text': 'Task 5', 'Shape': 'Rectangle', 'id': 4},   {'text': 'Task 6', 'Shape': 'Decision', 'id': 5}],  'links': [{'source': 0, 'target': 1, 'key': 0},   {'source': 0, 'target': 4, 'key': 0},   {'source': 1, 'target': 2, 'key': 0},   {'source': 1, 'target': 3, 'key': 0},   {'source': 2, 'target': 1, 'key': 0},   {'source': 2, 'target': 4, 'key': 0},   {'source': 3, 'target': 1, 'key': 0},   {'source': 3, 'target': 4, 'key': 0},   {'source': 4, 'target': 5, 'key': 0},   {'source': 5, 'target': 4, 'key': 0},   {'source': 5, 'target': 1, '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等等。我哪里出错了
查看完整描述

1 回答

?
FFIVE

TA贡献1797条经验 获得超6个赞

我无法重现错误,但json.dumps对我来说效果很好。请参考以下截图:

//img1.sycdn.imooc.com//64632c1300015efb21491294.jpg

我试过的代码:


import json

JsonData={'list': {'Elements': [{'text': 'Task 1', 'Shape': 'Decision', 'id': 0},

   {'text': 'Task 2', 'Shape': 'Decision', 'id': 1},

   {'text': 'Task 3', 'Shape': 'Decision', 'id': 2},

   {'text': 'Task 4', 'Shape': 'Decision', 'id': 3},

   {'text': 'Task 5', 'Shape': 'Rectangle', 'id': 4},

   {'text': 'Task 6', 'Shape': 'Decision', 'id': 5}],

  'links': [{'source': 0, 'target': 1, 'key': 0},

   {'source': 0, 'target': 4, 'key': 0},

   {'source': 1, 'target': 2, 'key': 0},

   {'source': 1, 'target': 3, 'key': 0},

   {'source': 2, 'target': 1, 'key': 0},

   {'source': 2, 'target': 4, 'key': 0},

   {'source': 3, 'target': 1, 'key': 0},

   {'source': 3, 'target': 4, 'key': 0},

   {'source': 4, 'target': 5, 'key': 0},

   {'source': 5, 'target': 4, 'key': 0},

   {'source': 5, 'target': 1, 'key': 0}]}}

print(type(JsonData))

print(json.dumps(JsonData))

print(type(json.dumps(JsonData)))


查看完整回答
反对 回复 2023-05-16
  • 1 回答
  • 0 关注
  • 98 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信