简体   繁体   English

通过Python中的值搜索从API返回的JSON

[英]Search JSON returned from API by value in Python

I'm accessing an API using Python 2.7.12 which gives a JSON response. 我正在使用Python 2.7.12访问一个提供JSON响应的API。 The JSON looks something like this: JSON看起来像这样:

{
    "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". 我正在使用Python将JSON解析为字符串,然后需要搜索JSON字符串并提取特定指标的值,因此在这种情况下,我需要指标“ 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. 我要继续做的是将“ Sales”中的值“ A”存储在名为totalSales的变量中,但是需要了解有关从JSON响应中查询和提取单个数据值的最佳做法,这是非常简单的API实际返回的版本。

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: 假设顺序始终与您通过键访问的顺序相同,那么您也不需要使用json.loads,因为请求可以为您处理:

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

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): json.loads为您提供了常规的Python嵌套字典,因此这样的方法应该可以工作(假设所需的数据条目始终是第一个):

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. 请注意,由于JSON的对象语法恰好与Python的字典语法相匹配,因此,如果要进行实验,可以将其粘贴到Python提示符中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM