从文件中读取JSON?我有点头疼,只是因为一个简单的样子,简单的陈述是把一些错误扔到了我的脸上。我有一个名为string s.json的json文件,如下所示:"strings": [{"-name": "city", "#text": "City"}, {"-name": "phone", "#text": "Phone"}, ...,
{"-name": "address", "#text": "Address"}]我想读一下JSON文件,只是暂时的。我有一些我发现的陈述,但它不起作用:import jsonfrom pprint import pprintwith open('strings.json') as json_data:
d = json.load(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]
3 回答
叮当猫咪
TA贡献1776条经验 获得超12个赞
json.load()
import jsonwith open('strings.json') as f: d = json.load(f) print(d)
json.loads()
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
import jsonwith open("test.json") as json_file: json_data = json.load(json_file) print(json_data)
{ "a": [1,3,"asdf",true], "b": { "Hello": "world" }}
至尊宝的传说
TA贡献1789条经验 获得超10个赞
从文件中读取并转换为JSON
import json# Considering "json_list.json" is a json filewith open('json_list.json') as fd: json_data = json.load(fd)
import json json_data = json.load(open('json_list.json'))
字符串到JSON
import json json_data = json.loads('{"name" : "myName", "age":24}')
添加回答
举报
0/150
提交
取消