问题:从文件读取JSON?

只是因为一个简单,易于表达的陈述使我的脸上有些错误,所以我有点头疼。

我有一个名为strings.json的json文件,如下所示:

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

我现在想读取json文件。我发现了以下这些语句,但是不起作用:

import json
from pprint import pprint

with open('strings.json') as json_data:
    d = json.loads(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.loadsjson.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]

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": [{"-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:

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.loads to 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]

回答 0

json.load()方法(“ load”中没有“ s”)可以直接读取文件:

import json

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

您正在使用json.loads()方法,该方法仅用于字符串参数。

编辑:新消息是一个完全不同的问题。在这种情况下,该文件中存在一些无效的json。为此,我建议通过json验证器运行文件。

还有一些修复json的解决方案,例如,如何自动修复无效的JSON字符串?

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)

You were using the json.loads() method, which is used for string arguments only.

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.

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


回答 1

这是一段代码,对我来说很好

import json

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

与数据

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

您可能想用try catch包装json.load行,因为无效的JSON会导致stacktrace错误消息。

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.


回答 2

问题是使用with语句:

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

该文件将已经隐式关闭。无需json_data.close()再次调用。

The problem is using with statement:

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.


回答 3

在python 3中,我们可以使用以下方法。

从文件读取并转换为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语句自动关闭打开的文件描述符。


字符串到JSON

import json
from pprint import pprint

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

In python 3, we can use below method.

Read from file and convert to 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.


String to JSON

import json
from pprint import pprint

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

回答 4

作为补充,今天您可以使用熊猫来导入json:
https : //pandas.pydata.org/pandas-docs/stable/genic/pandas.read_json.html 您可能要仔细使用Orient参数。

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.html You may want to do a careful use of the orient parameter.


回答 5

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

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

You can use pandas library to read the JSON file.

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

回答 6

这对我有用。

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

假设JSON文件是这样的:

{
   "emp_details":[
                 {
                "emp_name":"John",
                "emp_emailId":"john@gmail.com"  
                  },
                {
                 "emp_name":"Aditya",
                 "emp_emailId":"adityatest@yahoo.com"
                }
              ] 
}

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':'john@gmail.com'}
{'emp_name':'Aditya','emp_emailId':'adityatest@yahoo.com'}

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.

Suppose JSON file is like this:

{
   "emp_details":[
                 {
                "emp_name":"John",
                "emp_emailId":"john@gmail.com"  
                  },
                {
                 "emp_name":"Aditya",
                 "emp_emailId":"adityatest@yahoo.com"
                }
              ] 
}


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':'john@gmail.com'}
{'emp_name':'Aditya','emp_emailId':'adityatest@yahoo.com'}

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。