【问题标题】:json load is not correct (python) [duplicate]json加载不正确(python)[重复]
【发布时间】:2013-05-09 00:51:01
【问题描述】:

当我使用 json 保存 文件 中一切正常,但是当我 加载 加载的对象时不正确。

file=open("hello", "w")

a={'name':'jason', 'age':73, 'grade':{ 'computers':97, 'physics':95, 'math':89} }

json.dump(a, file)

正如我在文件中所说,没问题,但是当我加载时,您会发现问题。

文件:

" {"age": 73, "grade": {"computers": 97, "physics": 95, "math": 89}, "name": "jason"} "

现在加载:

b=json.load(file)

print b

输出:

{u"age": 73, u"grade": {u"computers": 97, u"physics": 95, u"math": 89}, u"name": u"jason"}

您可以清楚地注意到,在每个字符串之前都有 u。它不会影响代码,但我不喜欢那里..

为什么会这样?

【问题讨论】:

标签: python json load


【解决方案1】:

它只是在表示中......它并不是真的存在它只是表示它是 unicode

print u"this" == "this"

不确定这需要自己的答案:/

【讨论】:

  • 我知道了,有没有办法去掉?
  • 我假设您没有运行 python 3.X。我相当肯定,如果你用 python 3.x 解释器运行它,你不会看到 unicode 'u'...我想你可以用 ascii 编码它并使用 str()?
  • @Ofek .T.:为什么要更改字符串的表示?如果你只是打印数据,一切都很好。
  • 只是想知道为什么如果可能的话
【解决方案2】:

这是一个将 unicode dict 转换为 utf8 dict 的函数。

def uni2str(input):
    if isinstance(input, unicode):
        return input.encode('utf-8')
    elif isinstance(input, dict):
        return {uni2str(key): uni2str(value) for key, value in input.items()}
    elif isinstance(input, list):
        return [uni2str(element) for element in input]
    else:
        return input

a = {u'name':u'Yarkee', u'age':23, u'hobby':[u'reading', u'biking']}

print(uni2str(a))

输出将是:

{'hobby': ['reading', 'biking'], 'age': 23, 'name': 'Yarkee'}

【讨论】:

    猜你喜欢
    • 2015-11-01
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多