亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法在 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對我來說效果很好。請參考以下截圖:

http://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 關注
  • 185 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號