Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Parsing JSON Data Set

I am trying to parse a JSON data set that looks something like this:

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

Lets assume that there can be many of these data sets.

I would like to iterate through each one of them and grab the "Name" and the "Campaign ID" parameter.

So far my code looks something like this:

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

Probably quite straight forward! I am not good with lists/dictionaries :(

like image 517
Aivoric Avatar asked May 21 '13 17:05

Aivoric


1 Answers

Access dictionaries with d[dict_key] or d.get(dict_key, default) (to provide default value):

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

I suggest you read something about dictionaries.

like image 140
Zac Avatar answered Sep 24 '22 16:09

Zac