我有一个包含多个测量值的 Json 文件,我只想获取“wind_speed_avg”值,如果有值,则还获取“ts”值并添加 lsid,但它不在同一路径中。
JSON 如下所示:
{'station_id_uuid': 'd0d1a311',
'sensors': [
{'lsid': 3531,
'data': [
{'bar_absolute': 29.836,
'bar_hi_at': 1727761555,
'ts': 1727762400
}
],
'sensor_type': 242,
'data_structure_type': 13
},
{'lsid': 3558,
'data': [
{'wind_speed_avg': 10,
'uv_dose': 0.12857144,
'wind_chill_last': 66.5,
'ts': 1727763300
},
{'wind_speed_avg': 12,
'uv_dose': 0.096428566,
'wind_chill_last': 65.8,
'ts': 1727762896
},
{'wind_speed_avg': 8.75,
'uv_dose': 0.074999996,
'wind_chill_last': 66.1,
'ts': 1727763665
}
],
'sensor_type': 43,
'data_structure_type': 11
}
],
'generated_at': 1734604671,
'station_id': 988
}
我正在使用这个Python脚本:
data = jmespath.search("""
sensors[].{
value: data[].wind_speed_avg,
time: data[].ts,
sensor_id: lsid
}
""", json_data)
我得到的结果是这样的:
[
{'value': [], 'time': [1727762400], 'sensor_id': 3531},
{'value': [10, 12, 8.75], 'time': [1727763300, 1727762896, 1727763665], 'sensor_id': 3558}
]
我希望结果是这样的:
[
{'value': None, 'time': 1727762400, 'sensor_id': 3531},
{'value': 10, 'time': 1727763300, 'sensor_id': 3558},
{'value': 12, 'time': 1727762896,'sensor_id': 3558},
{'value': 8.75, 'time': 1727763665,'sensor_id': 3558},
]
我想将节点sensor_id添加到字典中。 有什么想法我该怎么做吗?
终于找到了一种方法来做我需要的事情,这是我使用的功能:
def filter_measurement(stationid, measure, input_json):
if input_json:
data = jmespath.search("""
sensors[].{
value: data[].""" + measure + """,
time: data[].ts,
sensor_id: lsid
}
""", input_json)
result_dic = []
for i in data:
if i["value"]:
num_values = len(i["value"])
for val in range(num_values):
date_val = datetime.fromtimestamp(i["time"][val])
result_dic.append({"station_id": stationid, "sensor_id": i["sensor_id"], "measurement": measure, "datetime": str(date_val), "Year": date_val.year, "Month": date_val.month, "Day": date_val.day, "Hour": date_val.hour, "Minute": date_val.minute, "value": i["value"][val]})
return result_dic