Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse values from a JSON file in Python

Tags:

python

json

file

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"}
        }]
    }]
}
like image 388
PythonEnthusiast Avatar asked Apr 21 '26 21:04

PythonEnthusiast


1 Answers

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
like image 92
Burhan Khalid Avatar answered Apr 23 '26 10:04

Burhan Khalid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!