简体   繁体   English

如何从 JSON 文件中读取数据

[英]How to read data from JSON file

I have a JSON file with the following data:我有一个包含以下数据的 JSON 文件:

{
    "id": 1008, 
    "description": "Cheese, caraway", 
    "tags": [ ], 
    "manufacturer": "", 
    "group": "Dairy and Egg Products", 
    "portions": [
        {
            "amount": 1, 
            "unit": "oz", 
            "grams": 28.35
        }
    ], 
    "nutrients": [
        {
            "value": 25.18, 
            "units": "g", 
            "description": "Protein", 
            "group": "Composition"
        }, 
        {
            "value": 29.2, 
            "units": "g", 
            "description": "Total lipid (fat)", 
            "group": "Composition"
        }, 
        {
            "value": 3.06, 
            "units": "g", 
            "description": "Carbohydrate, by difference", 
            "group": "Composition"
        }, 
        {
            "value": 3.28, 
            "units": "g", 
            "description": "Ash", 
            "group": "Other"
        }
    ]
}

and I use the following codes to try to read from it:我使用以下代码尝试从中读取:

import json
path = 'C:\\Users\\IBM_ADMIN\\Desktop\\ml-1m\\food_nutrients_database - 副本.json'
data = open(path).read()
records = json.loads(data)

but I get the following error:但我收到以下错误:

records = json.loads(data)
ValueError: Expecting value: line 1 column 1 (char 0)

What's the problem here?这里有什么问题? I noticed the result returned from "data" begins with "'锘縶".我注意到从“data”返回的结果以“'锘絷”开头。 Could this be the reason?这可能是原因吗? If so, how can I resolve it?如果是这样,我该如何解决?

Don't do that.不要那样做。 Just pass the data from the file as a whole.只需将文件中的数据作为一个整体传递即可。

data = open(path).read()
records = json.loads(data)

You can make it even shorter by using load() , which takes the file object itself:您可以使用load()使其更短,它采用文件对象本身:

records = json.load(open(path))

What you are doing wrong is that you are reading each line from the JSON file and passing it to json.load() .你做错的是你从 JSON 文件中读取每一行并将其传递给json.load() Instead, all you need to do is open the file once, read the contents, and then pass it to the json.load() method.相反,您需要做的就是打开文件一次,读取内容,然后将其传递给json.load()方法。 That will work.那会起作用。

file_data = open(path).read()
json_data = json.loads(file_data)

Also, the posted JSON format is incorrect, so make sure your JSON format is correct.此外,发布的 JSON 格式不正确,因此请确保您的 JSON 格式正确。

You're reading the lines individually from strings.您正在从字符串中单独读取行。 Try this instead:试试这个:

import json

with open(path, 'r') as infile:
    data = json.load(infile)

json.loads is to load a string to a json object so be sure not to confuse it with json.load json.loads 是将一个字符串加载到一个 json 对象中,所以一定不要把它和 json.load 混淆

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM