我的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"}
}
答案 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"}
}