Python和Json:将多行输入数据输入Json

时间:2018-06-26 10:52:00

标签: python json python-3.x

我的python代码存在问题,需要创建多行JSON类型的数据。

def get_json_data(response):
 x ={}
 f ={}
 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):
            x[header.replace('la:','')] = dimension

            for i, values in enumerate(dateRangeValues):
                for metricHeader, value in zip(metricHeaders, values.get('values')):
                    x[metricHeader.get('name').replace('la:','')] = value

        f['dashboard'] = x
        print (json.dumps(f))
 print (json.dumps(f))

当前正在显示这些数据

{
  "dashboard": 
      {"bounces": "12", "userType": "Returning Visitor", "users": "3"}
}

但是我想要的输出是显示这种数据

{
 "dashboard": 
     {"bounces": "10", "userType": "New Visitor", "users": "15"},
     {"bounces": "12", "userType": "Returning Visitor", "users": "3"}
}

3 个答案:

答案 0 :(得分:2)

您的输出数据示例不是有效的json,但是可以解决此问题:

def get_json_data(response):
 x ={}
 f ={'dashboad' : []}
 ...
        f['dashboard'].append(x)
        print (json.dumps(f))
 print (json.dumps(f))

信息中心值应为列表,以便您可以附加不同的x结果

答案 1 :(得分:2)

您的格式应该是这样

df1 = {
    "dashboard":
        [{"bounces": "10", "userType": "New Visitor", "users": "15"},
         {"bounces": "12", "userType": "Returning Visitor", "users": "3"}]
}

否则它将给出错误

答案 2 :(得分:0)

您无法建立这种结构,因为python不允许这样做。 只需在您的终端中键入此内容,您就会了解结构错误

{
 "dashboard": 
     {"bounces": "10", "userType": "New Visitor", "users": "15"},
     {"bounces": "12", "userType": "Returning Visitor", "users": "3"}
}