I have a Json file with multiple measurements, I want to get only "wind_speed_avg" values, if there is a value then get also the "ts" value and add the lsid but it is not in the same path.
The JSON looks like this:
{'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
}
I`m using this python script:
data = jmespath.search("""
sensors[].{
value: data[].wind_speed_avg,
time: data[].ts,
sensor_id: lsid
}
""", json_data)
and the result I`m getting is this:
[
{'value': [], 'time': [1727762400], 'sensor_id': 3531},
{'value': [10, 12, 8.75], 'time': [1727763300, 1727762896, 1727763665], 'sensor_id': 3558}
]
I want the result to be this way:
[
{'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},
]
I want to add the node sensor_id to the dictionary.
Any ideas how can I do it?
2
Answers
Finally I found a way to do what I needed, this is the function I used:
Instead of the loops, you can use comprehensions. For example,
gives