首页 > 解决方案 > 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 列。每次测量一行。那么我现在该如何修改呢?

标签: pythonjsonpandas

解决方案


我认为最简单的方法是使用 pandas.DataFrame(json_data); 那么您可以通过以下方式访问这些信息:

  • pandas.DataFrame(json_data)['sensor-time']['time']
  • pandas.DataFrame(json_data)['content']['element]
  • pandas.DataFrame(json_data)['content']['element]

推荐阅读