我想将多个列表合并到一个JSON数组中。 这是我的两个列表:
address = ['address1','address2']
temp = ['temp1','temp2']
我通过以下调用合并两个列表,并创建一个JSON。
new_list = list(map(list, zip(address, temp)))
jsonify({
'data': new_list
})
这是我的通话结果:
{
"data": [
[
"address1",
"temp1"
],
[
"address2",
"temp2"
]
]
}
但是,我想收到以下问题。我该怎么做以及如何插入标识符address
和hello
。
{
"data": [
{
"address": "address1",
"temp": "temp1"
},
{
"address": "address2",
"temp": "temp2"
}
]
}
答案 0 :(得分:1)
您可以使用列表理解:
import json
address = ['address1','address2']
temp = ['temp1','temp2']
d = {'data': [{'address': a, 'temp': t} for a, t in zip(address, temp)]}
print( json.dumps(d, indent=4) )
打印:
{
"data": [
{
"address": "address1",
"temp": "temp1"
},
{
"address": "address2",
"temp": "temp2"
}
]
}
答案 1 :(得分:1)
您可以像这样更改现有代码。该lambda
函数将完成将其转换为字典的技巧。
address = ['address1','address2']
temp = ['temp1','temp2']
new_list = list(map(lambda x : {'address': x[0], 'temp': x[1]}, zip(address, temp)))
jsonify({
'data': new_list
})