【问题标题】:Error converting dict to json in python在python中将dict转换为json时出错
【发布时间】:2019-01-16 17:10:15
【问题描述】:

我的 dict 输出看起来像这样

在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

【问题讨论】:

  • 什么错误?显示完整的回溯
  • 请停止使用图片作为文字。我们无法从图像中复制和粘贴来尝试重现问题。并且错误消息必须是对问题的编辑,而不是评论中另一个图像的链接!
  • 错误消息中明确说明了原因(以及解决方法)。但在您使用错误文本编辑问题之前,我不会回答。
  • @SergeBallesta 抱歉,因为错误太大,所以我选择发布图片而不是文字。现在已编辑。

标签: python json dictionary


【解决方案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)

【讨论】:

    【解决方案2】:

    可以在python中使用json库

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

    这将给出一个 json 字符串

    【解决方案3】:

    只需使用json 模块:

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

    ensure_ascii 位用于避免任何编码/解码错误。

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 2019-10-08
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2018-01-08
      • 2018-11-15
      • 1970-01-01
      相关资源
      最近更新 更多