Codingo Codingo - 1 month ago 7
Python Question

Looping over JSON arrays and printing data

I have a series of JSON files in a folder that look like the following:

{
"details": {
"firstName": "Test",
"surname": "Testmaker",
"email": "test@testhealth.com",
"phone": null,
"organisation": "Test Health",
"department": "B Ward",
"persona": "Health professionals",
"address": {
"street": "137 Test Street",
"suburb": "Test Park",
"postcode": null
},
"questions": {
"iAmA": null,
"iWorkAtA": "Private Hospital",
"iAmSeekingFor": null,
"iAmAMemberOf": null,
"furtherInfoOptIn": null,
"newsletterOptIn": "false",
"privacyCollection": true
}
},
"orders": [
{
"name": "A Guide to Relaxation",
"quantity": 20
},
{
"name": "Guide to Coping with Testing",
"quantity": 20
}
]
}


I'm trying to iterate over all of the JSON files and print the name of each order, and then the items that person has ordered.

I've successfully printed out the full names of all orders using the following:

import os, json

ordersDirectory = "C:\dev\cic\\testing"

# json objects stored in multiple files, itterate over all of them
for filename in os.listdir(ordersDirectory):
with open(ordersDirectory + '\\' + filename) as data_file:
dataset = json.load(data_file)
print(dataset["details"]["firstName"] + " " + dataset["details"]["surname"])


I now want to print all orders for those names however I'm struggling to work out how I loop over the orders object within the dataset I've created. Assuming the following is pseudo-code, what do I need to learn to make it work?

import os, json

ordersDirectory = "C:\dev\cic\\testing"

# json objects stored in multiple files, itterate over all of them
for filename in os.listdir(ordersDirectory):
with open(ordersDirectory + '\\' + filename) as data_file:
dataset = json.load(data_file)
print(dataset["details"]["firstName"] + " " + dataset["details"]["surname"])
# Broken pseudocode below
for items in dataset["orders"]:
print(items["orders"]["name"])

Answer

You were close

for order in dataset["orders"]:
     print(order["name"]+", quantity: " + str(order["quantity"]))
Comments