从文件中读取JSON?
我有点头疼,因为一个简单,易于表达的陈述使我的脸上有些错误.
I am getting a bit of headache just because a simple looking, easy statement is throwing some errors in my face.
我有一个名为strings.json的json文件,如下所示:
I have a json file called strings.json like this:
"strings": [{"-name": "city", "#text": "City"}, {"-name": "phone", "#text": "Phone"}, ...,
{"-name": "address", "#text": "Address"}]
我现在想读取json文件.我发现了以下这些语句,但是不起作用:
I want to read the json file, just that for now. I have these statements which I found out, but it's not working:
import json
from pprint import pprint
with open('strings.json') as json_data:
d = json.load(json_data)
json_data.close()
pprint(d)
控制台上显示的错误是这样的:
The error displayed on the console was this:
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]
json.load()
方法(加载"中没有"s")可以直接读取文件:
The json.load()
method (without "s" in "load") can read a file directly:
import json
with open('strings.json') as f:
d = json.load(f)
print(d)
您正在使用 json.loads()
方法,该方法仅用于 string 参数.
You were using the json.loads()
method, which is used for string arguments only.
新消息是一个完全不同的问题.在这种情况下,该文件中存在一些无效的json.为此,我建议通过 json验证器运行文件.
The new message is a totally different problem. In that case, there is some invalid json in that file. For that, I would recommend running the file through a json validator.
还有一些修复json的解决方案,例如如何我会自动修复无效的JSON字符串吗?.
There are also solutions for fixing json like for example How do I automatically fix an invalid JSON string?.