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

查看:28
本文介绍了从文件中读取 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.loads(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() 方法(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 的解决方案,例如 How如何自动修复无效的 JSON 字符串?.

There are also solutions for fixing json like for example How do I automatically fix an invalid JSON string?.

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

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