如何在Python中解析JSON文件中的值

时间:2013-09-19 04:41:10

标签: python json file

我正在尝试从json文件获取值,而我得到的错误是TypeError: expected string or buffer。我正确解析文件,而且我猜我的json文件格式也正确。我哪里错了?

两个文件都在同一目录中。

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 个答案:

答案 0 :(得分:11)

loads期望字符串不是文件句柄。您需要json.load

import json

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

答案 1 :(得分:1)

当您要加载 文件中的所有内容时,您正在尝试加载文件对象。做:

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

.read()从文件中获取所有内容并将其作为字符串返回。


with声明在这里也更加pythonic:

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