11

我正在尝试解析一个看起来像这样的 JSON 数据集:

{"data":[
    {
    "Rest":0,
    "Status":"The campaign is moved to the archive",
    "IsActive":"No",
    "StatusArchive":"Yes",
    "Login":"some_login",
    "ContextStrategyName":"Default",
    "CampaignID":1111111,
    "StatusShow":"No",
    "StartDate":"2013-01-20",
    "Sum":0,
    "StatusModerate":"Yes",
    "Clicks":0,
    "Shows":0,
    "ManagerName":"XYZ",
    "StatusActivating":"Yes",
    "StrategyName":"HighestPosition",
    "SumAvailableForTransfer":0,
    "AgencyName":null,
    "Name":"Campaign_01"
    },
    {
    "Rest":82.6200000000008,
    "Status":"Impressions will begin tomorrow at 10:00",
    "IsActive":"Yes",
    "StatusArchive":"No",
    "Login":"some_login",
    "ContextStrategyName":"Default",
    "CampaignID":2222222,
    "StatusShow":"Yes",
    "StartDate":"2013-01-28",
    "Sum":15998,"StatusModerate":"Yes",
    "Clicks":7571,
    "Shows":5535646,
    "ManagerName":"XYZ",
    "StatusActivating":"Yes",
    "StrategyName":"HighestPosition",
    "SumAvailableForTransfer":0,
    "AgencyName":null,
    "Name":"Campaign_02"
    }
    ]
}

让我们假设可以有许多这样的数据集。

我想遍历它们中的每一个并获取“名称”和“广告系列 ID”参数。

到目前为止,我的代码看起来像这样:

decoded_response = response.read().decode("UTF-8")
data = json.loads(decoded.response)

    for item in data[0]:
        for x in data[0][item] ...
            -> need a get name procedure
            -> need a get campaign_id procedure

可能非常直截了当!我不擅长列表/字典:(

4

1 回答 1

22

d[dict_key]使用or访问字典d.get(dict_key, default)(提供默认值):

jsonResponse=json.loads(decoded_response)
jsonData = jsonResponse["data"]
for item in jsonData:
    name = item.get("Name")
    campaignID = item.get("CampaignID")

我建议你读一些关于字典的东西。

于 2013-05-21T18:40:11.133 回答