代码之家  ›  专栏  ›  技术社区  ›  Michael A

循环JSON数组并打印数据

  •  0
  • Michael A  · 技术社区  · 8 年前

    我在一个文件夹中有一系列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"])
    

    现在我想打印这些名称的所有订单,但我正在努力找出如何在我创建的数据集中循环orders对象。假设以下是伪代码,我需要学习什么才能使其工作?

    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 回复  |  直到 8 年前
        1
  •  1
  •   Chris Kenyon    8 年前

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