在python中将dict转换为json时出错

时间:2018-08-09 09:35:14

标签: python json dictionary

我的字典输出看起来像这样 enter image description here

使用什么库将其转换为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

3 个答案:

答案 0 :(得分:1)

该错误是明确的:

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)

答案 1 :(得分:0)

只需使用json模块:

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

这里有ensure_ascii位是为了避免任何编码/解码错误。

答案 2 :(得分:0)

您可以在python中使用json库

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

这将给出一个json字符串