只是因为一个简单,易于表达的陈述使我的脸上有些错误,所以我有点头疼。
我有一个名为strings.json的json文件,如下所示:
"strings": [{"-name": "city", "#text": "City"}, {"-name": "phone", "#text": "Phone"}, ...,
{"-name": "address", "#text": "Address"}]
我现在想读取json文件。我发现了以下这些语句,但是不起作用:
import json
from pprint import pprint
with open('strings.json') as json_data:
d = json.loads(json_data)
json_data.close()
pprint(d)
控制台上显示的错误是这样的:
Traceback (most recent call last):
File "/home/.../android/values/manipulate_json.py", line 5, in <module>
d = json.loads(json_data)
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
[Finished in 0.1s with exit code 1]
已编辑
从更改json.loads
为json.load
并得到了:
Traceback (most recent call last):
File "/home/.../android/values/manipulate_json.py", line 5, in <module>
d = json.load(json_data)
File "/usr/lib/python2.7/json/__init__.py", line 278, in load
**kw)
File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 369, in decode
raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 829 column 1 - line 829 column 2 (char 18476 - 18477)
[Finished in 0.1s with exit code 1]
6
您确定文件包含有效的JSON吗?
—
爆炸药
另请参阅:JSON的读写示例
—
Martin Thoma
您的文件是无效的json格式。更改为:
—
krizex
{"strings": [{"-name": "city", "#text": "City"}, {"-name": "phone", "#text": "Phone"}, ..., {"-name": "address", "#text": "Address"}]}