从文件中读取JSON? [英] Reading JSON from a file?

查看:156
本文介绍了从文件中读取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?.

这篇关于从文件中读取JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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