Python 从文件中读取 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20199126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:50:49  来源:igfitidea点击:

Reading JSON from a file?

pythonjson

提问by R.R.C.

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. I have these statements which I found out, but it's not working:

我想读取 json 文件,现在就这样。我有我发现的这些陈述,但它不起作用:

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]

Edited

已编辑

Changed from json.loadsto 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]

采纳答案by ubomb

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 stringarguments only.

您使用的是仅用于字符串参数的json.loads()方法

Edit: 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 的解决方案,例如如何自动修复无效的 JSON 字符串?.

回答by user1876508

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 会导致堆栈跟踪错误消息。

回答by Zongjun

The problem is using withstatement:

问题是使用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()再次调用。

回答by Thejesh PR

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)

withstatement 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)

回答by Ando Jurai

To add on this, today you are able to use pandas to import json:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.htmlYou may want to do a careful use of the orient parameter.

补充一点,今天你可以使用 pandas 来导入 json:
https: //pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html你可能要小心使用 orient范围。

回答by drorhun

You can use pandas library to read the JSON file.

您可以使用 Pandas 库来读取 JSON 文件。

import pandas as pd
df = pd.read_json('strings.json',lines=True)
print(df)

回答by Aditya patil

This works for me.

这对我有用。

json.load()accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.

json.load()接受文件对象,解析 JSON 数据,用数据填充 Python 字典并将其返回给您。

Suppose JSON file is like this:

假设 JSON 文件是这样的:

{
   "emp_details":[
                 {
                "emp_name":"John",
                "emp_emailId":"[email protected]"  
                  },
                {
                 "emp_name":"Aditya",
                 "emp_emailId":"[email protected]"
                }
              ] 
}


import json 

# Opening JSON file 
f = open('data.json',) 

# returns JSON object as  
# a dictionary 
data = json.load(f) 

# Iterating through the json 
# list 
for i in data['emp_details']: 
    print(i) 

# Closing file 
f.close()

#Output:
{'emp_name':'John','emp_emailId':'[email protected]'}
{'emp_name':'Aditya','emp_emailId':'[email protected]'}