2

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.

0

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, that worked and an elegant solution, thanks
1

json.loads gives you a regular Python nested dictionary, so something like this should work (assuming the Data entry you want is always the first one):

for metric in data['Data'][0]['Metrics']:
    if metric['name'] == "Sales":
        totalSales = metric['values']['A']

Note that, because JSON's syntax for objects happens to match Python's syntax for dictionaries, you can just paste it into a Python prompt if you want to experiment.

1 Comment

I got the following error:Traceback (most recent call last): File "C:/Python27/practice1.py", line 35, in <module> totalSales = metric['A'] KeyError: 'A' >>>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.