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

标签 python json file

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

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

主文件.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 需要一个字符串而不是文件句柄。您需要 json.load:

import json

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

关于python - 如何在 Python 中解析 JSON 文件中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18886319/

相关文章:

python - 有没有办法分离 matplotlib 图以便计算可以继续?

python - 使用非标准 Python 安装

android - 我有两个 Activity 。我想将数据从第二个 Activity 发送到前一个 Activity 。第一个 Activity 有自定义 ListView

css - UI5 - 在 JSONView 中添加样式类

java - Dijkstra 算法的文件输入

python - Plotly:如何使用分组图例设置多个子图?

python - unittest.TestCase 的子类的子类,具有不同的 setUpClass 类方法

Swift 3 中的 JSON 解析

C# 将字节添加到文件的开头?

objective-c - MacOS 应用程序窗口内的文件管理器