0

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"
        }
    ]
}

2 Answers 2

1

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"
        }
    ]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Cool as easy. I could have come up with that myself. Thank you very much for your help. Really great.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.