I have the following JSON data (1st set below) followed by coding to load the json (2nd set below). I’m not figuring out how to iterate and append rows for each ‘stationID’ to extract ‘CircuitName’, ‘DewPoint’, and ‘WindSpeed’ under ‘values’:
ACTUAL JSON
[
{
"stationId": "X",
"date": "2024-08-14T08:00:00-07:00",
"values": {
"CircuitName": "Test",
"DewPoint": 39.39,
"WindSpeed": 5/5
}
},
{
"stationId": "Y",
"date": "2024-08-14T08:00:00-07:00",
"values": {
"CircuitName": "Test2",
"DewPoint": 55,
"WindSpeed": 0.888
}
}
]
CODE:
req = requests.get(api_request_url, params=params, headers=headers)
data = json.loads(req.text)
rows = []
for i in data:
row = {
"stationId": i["stationId"],
"CircuitName": i["values"],
}
rows.append(row)
2
Use a list comprehension to extract it directly(more efficient).
For example:
rows = [
{
"stationId": i["stationId"],
"CircuitName": i["values"]["CircuitName"],
"DewPoint": i["values"]["DewPoint"],
"WindSpeed": i["values"]["WindSpeed"]
}
for i in data
]
print(rows)
New contributor
Cp Gowtham is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.