I'm new to Python and I need some help to parse and insert this specific value from JSON file to CSV file.
Here's a snip of my JSON file
{
"data": [
{
"id": 5555,
"name": "Dodge RAM",
"pump": {
"50400": {
"device_id": 50400,
"type": "Diesel Car"
}
}
}
]
}
I want to get CSV output like this
id | name | device_id
5555 | Dodge RAM | 50400
Here's my Python code:
all_rows = response.json()
filename = "output.csv"
with open(filename, "w") as file:
csv_file = csv.writer(file, lineterminator='\n')
csv_file.writerow(["id", "name", "device_id"])
for item in all_rows["data"]:
csv_file.writerow([item['id'], item['name'], item['pump']['device_id'])
My code printed all value within pump "50400": {"device_id": 50400, "type": "Diesel Car"}
I only want device_id, I don't know how to skip "50400" in pump to get device_id. 50400 is not a constant value, it changes with device_id.
Any help is appreciated! Thank you!
Go over the dictionary items and select those whose key equals the 'device_id':
[
[vals['device_id'] for dev_id,vals in item["pump"].items()
if vals['device_id']==int(dev_id)]
for item in all_rows["data"]
]
#[[50400]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.