3

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"}
        }]
    }]
}
2
  • You meant json_data.close(), right? Commented Sep 19, 2013 at 4:42
  • Oops. Typo. Yes it is json_data.close Commented Sep 19, 2013 at 4:43

2 Answers 2

11

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
Sign up to request clarification or add additional context in comments.

1 Comment

Arg, forgot about json.load! +1 :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.