加载带有'u'作为json的python字符串 [英] Loading python string with 'u' as json

查看:249
本文介绍了加载带有'u'作为json的python字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在以下字符串中有一个字符串

I have a string in the following strings

json_string = '{u"favorited": false, u"contributors": null}'
json_string1 = '{"favorited": false, "contributors": null}'

以下json加载工作正常.

The following json load works fine.

json.loads(json_string1 )

但是,以下json加载给我值错误,该如何解决?

But, the following json load give me value error, how to fix this?

json.loads(json_string)
ValueError: Expecting property name: line 1 column 2 (char 1)

推荐答案

使用json.dumps将Python字典转换为字符串,而不是str.然后,您可以期望json.loads可以正常工作:

Use json.dumps to convert a Python dictionary to a string, not str. Then you can expect json.loads to work:

不正确:

>>> D = {u"favorited": False, u"contributors": None}
>>> s = str(D)
>>> s
"{u'favorited': False, u'contributors': None}"
>>> json.loads(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "D:\dev\Python27\lib\json\__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "D:\dev\Python27\lib\json\decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "D:\dev\Python27\lib\json\decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

正确:

>>> D = {u"favorited": False, u"contributors": None}
>>> s = json.dumps(D)
>>> s
'{"favorited": false, "contributors": null}'
>>> json.loads(s)
{u'favorited': False, u'contributors': None}

这篇关于加载带有'u'作为json的python字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆