简体   繁体   English

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

[英]Error converting dict to json in python

my dict output looks like this 我的字典输出看起来像这样 在此处输入图片说明

What library to use to convert it to json in python? 使用什么库将其转换为python中的json?

edit 1: my code now looks like 编辑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)

and it shows this error 它显示此错误

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

The error is explicit: 该错误是明确的:

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

By default the json module cannot serialize any of the types from the datetime module, and your dictionary contains ..., u'InstanceCreateTime': datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc()) , and other datetimes later. 默认情况下, json模块无法序列化datetime模块中的任何类型,并且您的词典包含..., u'InstanceCreateTime': datetime.datetime(2017, 6, 6, 9, 7, 33, 472000, tzinfo=tzutc())以及其他日期时间之后。

The idiomatic way is to define a custom encoder to process the relevant objects. 惯用的方法是定义一个自定义编码器来处理相关对象。 It is enough to override the default method, process the specific objects and pass everything else to the base class method: 覆盖默认方法,处理特定对象并将其他所有内容传递给基类方法就足够了:

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)

You can then use it to build your json: 然后,您可以使用它来构建json:

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

Just use the json module: 只需使用json模块:

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

The ensure_ascii bit is there to avoid any encoding/decoding errors. ensure_ascii位用于避免任何编码/解码错误。

You can use the json library in python 您可以在python中使用json库

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

This will give a json string 这将给出一个json字符串

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM