Accessing values from json in Pylons
-
29-05-2021 - |
Question
In my controller I'm getting a json string (called c.order_history
which looks like:
[
{
"status": [
{
"status": "created",
"timestamp": "2012-04-06 00:14:10"
},
{
"status": "authed",
"timestamp": "2012-04-06 00:14:17"
}
],
"product_info": [
{
"id": 3,
"quantity": 1,
"created": "2012-04-06 00:14:10",
"image_id": 13341
},
{
"id": 2,
"quantity": 1,
"created": "2012-04-06 00:14:10",
"image_id": 13323
},
{
"id": 1,
"quantity": 1,
"created": "2012-04-06 00:14:10",
"image_id": 13322
}
],
"shipping_charge": "0.00",
"order_number": "0723094747433",
"shipping_address": {
"country_code": null,
"extended_address": "Unit Z",
"locality": "Las Vagas",
"company": null,
"phone": null,
"postal_code": "31415",
"full_name": "Boris Karloff",
"nickname": null,
"region": "NV",
"street_address": "123 Random Way"
},
"subtotal": "59.00"
}
]
I'm passing it through json.loads(order_history)
to turn it into a dict, and then trying to extract each key so I can then get the subsequent key/values within them like:
c.product_info = [{'product_info' : product_info} for product_info in c.order_history]
Which outputs the entire json string, but it's just named product_info
now. Can someone steer me in the right direction on how I can access say, the timestamp
value, product_info[0]['image_id']
and shipping_address
values, etc.?
Solution
It looks like c.order_history
will be a list of dictionaries, to just grab the product_info
key from each of these dictionaries in a list comprehension you would do the following:
[{'product_info': order['product_info']} for order in c.order_history]