尝试在Python中解析JSON. ValueError:期望的属性名称 [英] Trying to parse JSON in Python. ValueError: Expecting property name
问题描述
我正在尝试将JSON对象解析为Python dict
.我以前从未做过.当我搜索这个特定错误(第一个字符有什么问题吗?)时,其他帖子都说正在加载的字符串实际上不是JSON字符串.我很确定是这样.
I am trying to parse a JSON object into a Python dict
. I've never done this before. When I googled this particular error, (What is wrong with the first char?), other posts have said that the string being loaded is not actually a JSON string. I'm pretty sure this is, though.
在这种情况下,eval()
可以正常工作,但是我想知道是否还有更合适的方法?
In this case, eval()
works fine, but I'm wondering if there is a more appropriate way?
注意::该字符串直接通过ptt工具来自Twitter.
Note: This string comes directly from Twitter, via ptt tools.
>>> import json
>>> line = '{u\'follow_request_sent\': False, u\'profile_use_background_image\': True,
u\'default_profile_image\': False,
u\'verified\': False, u\'profile_sidebar_fill_color\': u\'DDEEF6\',
u\'profile_text_color\': u\'333333\', u\'listed_count\': 0}'
>>> json.loads(line)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 1 (char 1)
推荐答案
那绝对不是JSON-无论如何都不是上面打印的.它已经被解析为Python对象-JSON将具有false
而不是False
,并且对于unicode而言,其字符串不会显示为u
(所有JSON字符串均为unicode).您确定不是已经将json字符串免费转换为链中某处的Python对象,因此将其加载到json.loads()显然是错误的,因为实际上它不是字符串吗?
That's definitely not JSON - not as printed above anyhow. It's already been parsed into a Python object - JSON would have false
, not False
, and wouldn't show strings as u
for unicode (all JSON strings are unicode). Are you sure you're not getting your json string turned into a Python object for free somewhere in the chain already, and thus loading it into json.loads() is obviously wrong because in fact it's not a string?
这篇关于尝试在Python中解析JSON. ValueError:期望的属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!