簡體   English   中英

在python中將dict轉換為json時出錯

[英]Error converting dict to json in python

我的字典輸出看起來像這樣 在此處輸入圖片說明

使用什么庫將其轉換為python中的json?

編輯1:我的代碼現在看起來像

import boto3
import json
rds_client = boto3.client('rds', 'ap-southeast-1')
db_instance_info = rds_client.describe_db_instances()
with open('result.json', 'w') as db:
    json.dump(db_instance_info, db)

它顯示此錯誤

Traceback (most recent call last):
  File "list.py", line 14, in <module>
    json.dump(db_instance_info, db)
  File "/usr/lib/python2.7/json/__init__.py", line 189, in dump
    for chunk in iterable:
  File "/usr/lib/python2.7/json/encoder.py", line 434, in _iterencode
    for chunk in _iterencode_dict(o, _current_indent_level):
  File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 332, in _iterencode_list
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 408, in _iterencode_dict
    for chunk in chunks:
  File "/usr/lib/python2.7/json/encoder.py", line 442, in _iterencode
    o = _default(o)
  File "/usr/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc()) is not JSON serializable

該錯誤是明確的:

TypeError: datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc()) is not JSON serializable

默認情況下, json模塊無法序列化datetime模塊中的任何類型,並且您的詞典包含..., u'InstanceCreateTime': datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc())以及其他日期時間之后。

慣用的方法是定義一個自定義編碼器來處理相關對象。 覆蓋默認方法,處理特定對象並將其他所有內容傳遞給基類方法就足夠了:

class DateEncoder(json.JSONEncoder):
"""This encoder only use the default string convertion for the types
date, time and datetime of the datetime module"""
    def default(self, o):
        if (isinstance(o, datetime.date)
            or isinstance(o, datetime.datetime)
            or isinstance(o, datetime.time)):
            return str(o)                # specialize here the format...
        return json.JSONEncoder.default(self, o)

然后,您可以使用它來構建json:

with open('result.json', 'w') as db:
    json.dump(db_instance_info, db, cls=DateEncoder)

只需使用json模塊:

import json
jsonarray = json.dumps(the_dict, ensure_ascii=False)

ensure_ascii位用於避免任何編碼/解碼錯誤。

您可以在python中使用json庫

import json
x = {'s': True}
r = json.dumps(x)

這將給出一個json字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM