【问题标题】:Writing dictionary to JSON then back into Python yields Unicode not dictionary将字典写入 JSON 然后返回到 Python 会产生 Unicode 而不是字典
【发布时间】:2016-05-12 22:10:57
【问题描述】:

我的工作正常,但是当有一个日期时,我必须编写一个函数来序列化它以使用JSON,但是当我从JSON 读回它时,它似乎进来了作为 unicode,而不是字典。

from collections import OrderedDict
import json
import datetime

def date_handler(obj):
    return obj.isoformat() if hasattr(obj, 'isoformat') else obj

d = OrderedDict([(1, {'test': datetime.datetime(2016, 2, 1, 20, 21, 27)}), (2, 20)])

d =  json.dumps(d, default=date_handler)

with open("my_file.json","w") as f:
    json.dump(d,f)

with open('my_file.json') as data_file:
    data = json.load(data_file)
print data

print type(data)
for key, value in data.iteritems():
    print key, value

错误:

AttributeError: 'unicode' object has no attribute 'iteritems'

【问题讨论】:

  • dump 两次,所以你的文件中有奇怪的数据。
  • @furas 我认为可能是这种情况,我不太确定dumps 函数在做什么,我应该删除哪个,我该怎么做?

标签: python json python-2.7 dictionary unicode


【解决方案1】:

你只需要一个dump

d = OrderedDict([(1, {'test': datetime.datetime(2016, 2, 1, 20, 21, 27)}), (2, 20)])

with open("my_file.json","w") as f:
    json.dump(d, f, default=date_handler)

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 2014-10-26
    • 2018-11-01
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多