从文件中读取JSON?

本文翻译自:Reading JSON from a file?

I am getting a bit of headache just because a simple looking, easy statement is throwing some errors in my face. 只是因为一个简单,易于表达的陈述使我的脸上有些错误,所以我有点头疼。

I have a json file called strings.json like this: 我有一个名为strings.json的json文件,如下所示:

"strings": [{"-name": "city", "#text": "City"}, {"-name": "phone", "#text": "Phone"}, ...,
            {"-name": "address", "#text": "Address"}]

I want to read the json file, just that for now. 我想立即读取json文件。 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]

Edited 已编辑

Changed from json.loads to json.load json.loads更改为json.load

and got this: 并得到了:

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]

#1楼

参考:https://stackoom.com/question/1mKIm/从文件中读取JSON


#2楼

The json.load() method (without "s" in "load") can read a file directly: json.load()方法 (“ load”中没有“ s”)可以直接读取文件:

import json

with open('strings.json') as f:
    d = json.load(f)
    print(d)

You were using the json.loads() method , which is used for string arguments only. 您正在使用json.loads()方法 ,该方法仅用于字符串参数。

Edit: The new message is a totally different problem. 编辑:新消息是一个完全不同的问题。 In that case, there is some invalid json in that file. 在这种情况下,该文件中存在一些无效的json。 For that, I would recommend running the file through a json validator . 为此,我建议通过json验证程序运行文件。

There are also solutions for fixing json like for example How do I automatically fix an invalid JSON string? 还有一些修复json的解决方案,例如, 如何自动修复无效的JSON字符串? .


#3楼

Here is a copy of code which works fine for me 这是一段代码,对我来说很好

import json

with open("test.json") as json_file:
    json_data = json.load(json_file)
    print(json_data)

with the data 与数据

{
    "a": [1,3,"asdf",true],
    "b": {
        "Hello": "world"
    }
}

you may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message. 您可能想用try catch包装json.load行,因为无效的JSON会导致stacktrace错误消息。


#4楼

The problem is using with statement: 问题是使用with语句:

with open('strings.json') as json_data:
    d = json.load(json_data)
    pprint(d)

The file is going to be implicitly closed already. 该文件将已经隐式关闭。 There is no need to call json_data.close() again. 无需再次调用json_data.close()


#5楼

In python 3, we can use below method. 在python 3中,我们可以使用以下方法。

Read from file and convert to JSON 从文件读取并转换为JSON

import json
from pprint import pprint

# Considering "json_list.json" is a json file

with open('json_list.json') as fd:
     json_data = json.load(fd)
     pprint(json_data)

with statement automatically close the opened file descriptor. with语句自动关闭打开的文件描述符。


String to JSON 字符串到JSON

import json
from pprint import pprint

json_data = json.loads('{"name" : "myName", "age":24}')
pprint(json_data)

#6楼

To add on this, today you are able to use pandas to import json: 作为补充,今天您可以使用pandas导入json:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html You may want to do a careful use of the orient parameter. https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html您可能要仔细使用orient参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值