从嵌套的JSON文件中提取值

时间:2019-05-16 13:23:07

标签: python json extract

我正在尝试从空气质量传感器中提取值,以将其显示在设备上。我无法提取温度,湿度和PM传感器的嵌套值。如何获取它们作为单独的键和值?

我确实安装了pandas ant并尝试了其他解决方案:

import pandas as pd

url = 'http://192.168.0.117/data.json'
df = pd.read_json(url, orient='columns')

print (df)

import urllib.request, json
with urllib.request.urlopen("http://192.168.0.117/data.json") as url:
    data = json.loads(url.read().decode())
    print (data)

我得到的是值列表:

{
  "software_version": "NRZ-2018-123B",
  "age": "28",
  "sensordatavalues": [
    {
      "value_type": "SDS_P1",
      "value": "18.40"
    },
    {
      "value_type": "SDS_P2",
      "value": "10.33"
    },
    {
      "value_type": "temperature",
      "value": "9.50"
    },
    {
      "value_type": "humidity",
      "value": "99.90"
    },
    {
      "value_type": "samples",
      "value": "1753691"
    },
    {
      "value_type": "min_micro",
      "value": "80"
    },
    {
      "value_type": "max_micro",
      "value": "793061"
    },
    {
      "value_type": "signal",
      "value": "-73"
    }
  ]
}

如何将它们作为单独的变量获取?

2 个答案:

答案 0 :(得分:0)

您需要先将json展平,然后再将其读入熊猫。 json_normalize似乎是您所需要的。这是一个教程:

https://www.kaggle.com/jboysen/quick-tutorial-flatten-nested-json-in-pandas

答案 1 :(得分:0)

恭喜您开始使用python!这是进行数据分析的好工具。

butterflyknife是正确的,json_normalize是在这里使用的好工具。

我在本地尝试过

import urllib.request
import json 
import pandas as pd 
from pandas.io.json import json_normalize 

sample_data = '{"software_version": "NRZ-2018-123B", "age":"28", "sensordatavalues":[{"value_type":"SDS_P1","value":"18.40"},{"value_type":"SDS_P2","value":"10.33"},{"value_type":"temperature","value":"9.50"},{"value_type":"humidity","value":"99.90"},{"value_type":"samples","value":"1753691"},{"value_type":"min_micro","value":"80"},{"value_type":"max_micro","value":"793061"},{"value_type":"signal","value":"-73"}]}'

y = json.loads(sample_data)
y2 = json_normalize(y["sensordatavalues"])

该样本数据现在为y2,数据帧如下所示:

# >>> y2
#      value   value_type
# 0    18.40       SDS_P1
# 1    10.33       SDS_P2
# 2     9.50  temperature
# 3    99.90     humidity
# 4  1753691      samples
# 5       80    min_micro
# 6   793061    max_micro
# 7      -73       signal