对大查询表的API请求

时间:2018-07-31 12:22:30

标签: python json api

我面临一个问题,关于使用python修改JSON文件的好方法

JSON请求:

{
    "reports": [{
            "data": {
                "rows": [{
                        "metrics": [{
                                "values": ["27.8", "4", "4", "6.95", "1.0", "0.0", "3.8834951456310676"]
                            }
                        ],
                        "dimensions": ["TEST1", "20180725"]
                    }, {
                        "metrics": [{
                                "values": ["75.0", "12", "12", "6.25", "1.0", "0.0", "3.4782608695652173"]
                            }
                        ],
                        "dimensions": ["TEST2", "20180725"]
                    }
                ],
                "maximums": [{
                        "values": ["1665.0", "140", "126", "65.0", "3.0", "0.0", "50.0"]
                    }
                ],
                "minimums": [{
                        "values": ["0.0", "0", "0", "0.0", "0.0", "0.0", "0.0"]
                    }
                ],
                "isDataGolden": true,
                "totals": [{
                        "values": ["27045.99", "3274", "2831", "8.260839951130116", "1.1564818085482163", "0.0", "4.949387227049424"]
                    }
                ],
                "rowCount": 358
            },
            "columnHeader": {
                "dimensions": ["ga:productName", "ga:date"],
                "metricHeader": {
                    "metricHeaderEntries": [{
                            "type": "CURRENCY",
                            "name": "ga:itemRevenue"
                        }, {
                            "type": "INTEGER",
                            "name": "ga:itemQuantity"
                        }, {
                            "type": "INTEGER",
                            "name": "ga:uniquePurchases"
                        }, {
                            "type": "CURRENCY",
                            "name": "ga:revenuePerItem"
                        }, {
                            "type": "FLOAT",
                            "name": "ga:itemsPerPurchase"
                        }, {
                            "type": "CURRENCY",
                            "name": "ga:productRefundAmount"
                        }, {
                            "type": "PERCENT",
                            "name": "ga:buyToDetailRate"
                        }
                    ]
                }
            }
        }
    ]
}

寻找:

基于“尺寸” “ metricHeaderEntries”

的矩阵中的值

修改(或重新创建)报告的干净方法是什么

LINE1 - {"ga:productName": "NAME","ga:date": "NAME","ga:itemRevenue": "value1", "ga:itemQuantity": "value2", ... }
LINE2 - {"ga:productName": "NAME","ga:date": "NAME","ga:itemRevenue": "value1", "ga:itemQuantity": "value2", ... }

EDIT1:

{
"ga:productName": "NAME", #from dimension 
"ga:date": "NAME", #from dimension 
"ga:itemRevenue": "value1", #from metricHeaderEntries 
"ga:itemQuantity": "value2", #from metricHeaderEntries 
... 
}
{
"ga:productName": "NAME2", #from dimension 
"ga:date": "NAME2", #from dimension 
"ga:itemRevenue": "value3", #from metricHeaderEntries 
"ga:itemQuantity": "value4", #from metricHeaderEntries 
... 
}

以这种方式工作的价值:

"metrics": [{"values": ["27.8", "4", "4", "6.95", "1.0", "0.0","3.8834951456310676"] #headers in metricHeaderEntries 
"dimensions": ["TEST1", "20180725"] #header in dimension 

或相似(我对总计不感兴趣,依此类推)

寻找解决方案/样本/说明,以及BQ接受方式。

额外:

我了解从JSON请求中获取数据的方式,例如:

responce[][][]

但是这种情况对我来说太棘手了(

示例:

理想情况下,这是表格的外观 THIS IS HOW IDEALLY TABLE SHOULD LOOK LIKE

这是google提供的打印此数据的方式(但需要将其转换为我上面解释的格式

def print_response(response):
  for report in response.get('reports', []):
    columnHeader = report.get('columnHeader', {})
    dimensionHeaders = columnHeader.get('dimensions', [])
    metricHeaders = columnHeader.get('metricHeader', {}).get('metricHeaderEntries', [])

    for row in report.get('data', {}).get('rows', []):
      dimensions = row.get('dimensions', [])
      dateRangeValues = row.get('metrics', [])

      for header, dimension in zip(dimensionHeaders, dimensions):
        print header + ': ' + dimension

      for i, values in enumerate(dateRangeValues):
        print 'Date range: ' + str(i)
        for metricHeader, value in zip(metricHeaders, values.get('values')):
          print metricHeader.get('name') + ': ' + value

1 个答案:

答案 0 :(得分:0)

因此您的编辑仍与JSON不匹配;在维度上,您有一个值列表,而不是键:值

"dimensions": [
          "ga:productName",
          "ga:date"
        ],

这意味着您没有任何价值,因此您的示例不正确。 在“ metricHeaderEntries”中,您将具有以下内容:

"metricHeader": {
          "metricHeaderEntries": [
            {
              "type": "CURRENCY",
              "name": "ga:itemRevenue"
            },
            {
              "type": "INTEGER",
              "name": "ga:itemQuantity"
            },
            {
              "type": "INTEGER",
              "name": "ga:uniquePurchases"
            },
            {
              "type": "CURRENCY",
              "name": "ga:revenuePerItem"
            },
            {
              "type": "FLOAT",
              "name": "ga:itemsPerPurchase"
            },
            {
              "type": "CURRENCY",
              "name": "ga:productRefundAmount"
            },
            {
              "type": "PERCENT",
              "name": "ga:buyToDetailRate"
            }
          ]
        }

因此即使在这种情况下也与您的示例不匹配,因为在“ metricHeaderEntries”下您没有示例中显示的“ ga:itemRevenue”或“ ga:itemQuantity”值。

无论如何,您都可以像使用python字典一样实现JSON的正确性,因此,在字典的情况下可以通过键选择元素,在列表的情况下可以通过索引来选择元素。

如果有时间我会尝试解决您的问题,即使您提供的节点不正确,也可以从示例中获取值。

答案:

即使我对键值进行了硬编码而不是从原始JSON中提取代码也只是为了让您了解其工作原理,我还是解决了您的问题;请让我知道这是否是您所期望的:

new_list=[]

l=a["reports"][0]["data"]["rows"]#get to "rows" key from a, where a is your JSON readed as dictionary
for i in l:#iterate rows key for search the needed values for each lines
    dict_line={}#create a dictionary for each line
    dict_line["ga:productName"]=i["dimensions"][0]#add to the dictionary dict_lineth key ga:productName and the product name as value
    dict_line["ga:date"]=i["dimensions"][1]#add to the dictionary dict_lineth key ga:date and the product date as value
    j= (i["metrics"][0]['values'])#for each product line I create a key node and value
    dict_line["ga:itemRevenue"]=j[0]
    dict_line["ga:itemQuantity"]=j[1]
    dict_line["ga:uniquePurchases"]=j[2]
    dict_line["ga:revenuePerIte"]=j[3]
    dict_line["ga:itemsPerPurchase"]=j[4]
    dict_line["ga:productRefundAmount"]=j[5]
    dict_line["ga:buyToDetailRate"]=j[6]
    new_list.append(dict_line)

print (new_list)

这是结果:

[
  {
    "ga:productName": "TEST1",
    "ga:itemRevenue": "27.8",
    "ga:uniquePurchases": "4",
    "ga:date": "20180725",
    "ga:revenuePerIte": "6.95",
    "ga:productRefundAmount": "0.0",
    "ga:itemQuantity": "4",
    "ga:itemsPerPurchase": "1.0",
    "ga:buyToDetailRate": "3.8834951456310676"
  },
  {
    "ga:productName": "TEST2",
    "ga:itemRevenue": "75.0",
    "ga:uniquePurchases": "12",
    "ga:date": "20180725",
    "ga:revenuePerIte": "6.25",
    "ga:productRefundAmount": "0.0",
    "ga:itemQuantity": "12",
    "ga:itemsPerPurchase": "1.0",
    "ga:buyToDetailRate": "3.4782608695652173"
  }
]