megatron77 megatron77 - 4 months ago 17
JSON Question

Search JSON returned from API by value in Python

I'm accessing an API using Python 2.7.12 which gives a JSON response. The JSON looks something like this:

{
"Header": {
"GeneratedAt": "2016-07-31T13:42:33",
"PeriodA": {
"startDate": "20160718",
"type": "WEEKLY",
"endDate": "20160724"
}
},
"Data": [
{
"Metrics": [
{
"name": "Sales",
"values": {
"A": "823456.32",
"B": ""
},
"id": "TL_TOTAL_SALES"
},
{
"name": "Orders",
"values": {
"A": "1230",
"B": ""
},
"id": "TL_TOTAL_ORDERS"
},
],
"label": "Commerce Metrics"
},
]
}


I'm parsing the JSON as a string using Python and then I need to search the JSON string and extract the values of a particular metric, so in this case I want the values of the metric "Sales".

My code so far:

import json, requests

url = "https://something.com/blah-blah-blah/"
r = requests.get(url)
data = json.loads(r.text)
print json.dumps(data, indent=4)


What I want to go on to do is store the value "A" from "Sales" in a variable called totalSales but need to know the best practices on querying and extracting individual data values from a JSON response like this, this is a very stripped down version of what actually gets returned from the API.

Answer

Presuming the order is always the same you just access by key, you also don't need to use json.loads as requests can handle that for you:

js = requests.get(url).json()

total_sales = js["Data"][0]['Metrics'][0]["values"]["A"]

print(total_sales)

If the order can be different, just iterate until you find the dict then break:

js = requests.get(url).json()
for dct in js["Data"][0]['Metrics']:
    if dct.get("name") == "Sales":
        total_sales = dct["values"]["A"]
        break