matt-rock
matt-rock

Reputation: 133

Python: Combine multiple lists into one JSON array

I want to merge several lists into one JSON array. These are my two lists:

address =  ['address1','address2']
temp = ['temp1','temp2']

I combine both lists by the following call and create a JSON .

new_list = list(map(list, zip(address, temp)))
jsonify({
    'data': new_list
})

This is my result for the call:

{
    "data": [
        [
            "address1",
            "temp1"
        ],
        [
            "address2",
            "temp2"
        ]
    ]
}

However, I would like to receive the following issue. How do I do that and how can I insert the identifier address and hello.

{
    "data": [
        {
            "address": "address1",
            "temp": "temp1"
        },
        {
            "address": "address2",
            "temp": "temp2"
        }
    ]
}

Upvotes: 0

Views: 2076

Answers (2)

Praveenkumar
Praveenkumar

Reputation: 2182

You can just change your existing code like this. That lambda function will do the trick of converting it into a dict.

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
})

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195408

You can use a list-comprehension:

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) )

Prints:

{
    "data": [
        {
            "address": "address1",
            "temp": "temp1"
        },
        {
            "address": "address2",
            "temp": "temp2"
        }
    ]
}

Upvotes: 1

Related Questions