python - Python - 规范化嵌套的 json 文件
问题描述
我有嵌套的 json 文件,我正在尝试将数据放入数据框中。我必须提取传感器时间,然后是元素,最后是传感器信息。这是 json 文件的样子:
{
"sensor-time": {
"timezone": "America/Los_Angeles",
"time": "2019-11-21T01:00:04-08:00"
},
"status": {
"code": "OK"
},
"content": {
"element": [{
"element-id": 0,
"element-name": "Line 0",
"sensor-type": "SINGLE_SENSOR",
"data-type": "LINE",
"from": "2019-11-21T00:00:00-08:00",
"to": "2019-11-21T01:00:00-08:00",
"resolution": "ONE_HOUR",
"measurement": [{
"from": "2019-11-21T00:00:00-08:00",
"to": "2019-11-21T01:00:00-08:00",
"value": [{
"value": 0,
"label": "fw"
}, {
"value": 0,
"label": "bw"
}
]
}
]
}
]
},
"sensor-info": {
"serial-number": "D8:80:39:D9:6B:9B",
"ip-address": "192.168.0.3",
"name": "XD01",
"group": "Boost Mobile",
"device-type": "PC2"
}
}
到目前为止,这是我的代码:
import json
from pandas.io.json import json_normalize
import glob
import urllib
import sqlalchemy as sa
# Create empty dataframe
# Drill through each file with json extension in the folder, open it, load it and parse it into dataframe
file = 'C:/Test/Loading/testfile.json'
with open(file) as json_file:
json_data = json.load(json_file)
df = json_normalize(json_data, meta=['sensor-time'])
df
这是我运行代码时的输出:
我尝试使用 flatten_json 库,我能得到的最好的就是使用以下代码:
with open(file) as json_file:
json_data = json.load(json_file)
flat = flatten_json(json_data)
df = json_normalize(flat)
我得到一行 33 列的输出。因此,在我的情况下,由于我在 json 文件的测量部分下有多个值,因此我得到了每个测量值的列。我必须得到的是 3 行 24 列。每次测量一行。那么我现在该如何修改呢?
解决方案
我认为最简单的方法是使用 pandas.DataFrame(json_data); 那么您可以通过以下方式访问这些信息:
- pandas.DataFrame(json_data)['sensor-time']['time']
- pandas.DataFrame(json_data)['content']['element]
- pandas.DataFrame(json_data)['content']['element]
推荐阅读
- c# - System.UnauthorizedAccessException:访问路径:PATH 被拒绝
- c# - 从另一个泛型类类型实例化泛型类型
- websocket - 如何在真实世界的应用程序中使用 Jetty 的 onWebSocketBinary API
- c# - 如何更新由 Microsoft.AspNet.Scaffolding 为 aspnetcore 编码的 CodeGenerator?
- rdf - 是否可以在 JSON-LD 上下文文件中为同一个谓词分配两个不同的别名?
- css - 如何使图像作为div的封面?
- mysql - 日期范围内的 COUNT CASE 函数
- mingw - Codelite/Mingw 运行测试构建而不是我想要的文件
- javascript - 使用下拉菜单更改元素的颜色
- wildfly - Wildfly16 使用 mqtt 支持设置嵌入式 Artemis