循环JSON数组并打印数据

时间:2016-10-25 00:37:56

标签: python json python-3.x

我在一个文件夹中有一系列JSON文件,如下所示:

{
    "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
        }
    ]
}

我正在尝试迭代所有JSON文件并打印每个订单的名称,然后打印该人订购的商品。

我已成功使用以下内容打印出所有订单的全名:

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"])

我现在想要打印这些名称的所有订单,但是我正在努力弄清楚我是如何遍历我创建的数据集中的订单对象。假设以下是伪代码,我需要学习什么来使其工作?

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"])

1 个答案:

答案 0 :(得分:1)

你很亲密

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