简体   繁体   中英

How to parse values from a JSON file in Python

I'm trying to get the values from the json file and the error that I'm getting is TypeError: expected string or buffer . I'm parsing the file correctly and moreover I guess my json file format is also correct. Where I'm going wrong?

Both the files are in the same directory.

Main_file.py

import json

json_data = open('meters_parameters.json')

data = json.loads(json_data)  // TypeError: expected string or buffer
print data
json_data.close()

meters_parameters.json

{
    "cilantro" : [{
        "cem_093":[{
            "kwh":{"function":"3","address":"286","length":"2"},
            "serial_number":{"function":"3","address":"298","length":"2"},
            "slave_id":{"function":"3","address":"15","length":"2"}
        }]
    }],
    "elmeasure" : [{
        "lg1119_d":[{
            "kwh":{"function":"3","address":"286","length":"2"},
            "serial_number":{"function":"3","address":"298","length":"2"},
            "slave_id":{"function":"3","address":"15","length":"2"}
        }]
    }]
}

loads expects a string not a file handle. You need json.load :

import json

with open('meters_parameters.json') as f:
    data = json.load(f)
print data

You're trying to load the file object, when you want to load everything in the file. Do:

data = json.loads(json_data.read())

.read() gets everything from the file and returns it as a string.


A with statement is much more pythonic here as well:

with open('meters_parameters.json') as myfile:
    data = json.loads(myfile.read())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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