0

mcve :

d1 = {"a":1}
d2 = {"b":2}
import json
with open('test2.json','w+') as file:
     for d in [d1,d2]:
             json.dump(d,file)

test2.json content :

{"a": 1}{"b": 2}

Desired Result :

[{"a": 1},{"b": 2}]

How can I achieve it?

6 Answers 6

1
d1 = {"a":1}
d2 = {"b":2}
import json

array = [json.dumps(d) for d in [d1,d2]]

Then write array to file

Sign up to request clarification or add additional context in comments.

Comments

0

Create a list instead, and dump that list directly.

with open('test2.json','w+') as file:
     d = [d1, d2]
     json.dump(d,file)

1 Comment

This is not possible as in actual example in each iteration json object is being generated. So maybe I've to add those json in list and then finally dump those.
0

try this

d1 = {"a":1}
d2 = {"b":2}
import json
tab = [d1, d2]
with open('test2.json','w+') as file:
    json.dump(tab ,file)

Comments

0

Use list and append both the dictionary into list and then write list into the file.

d1 = {"a":1}
d2 = {"b":2}
import json
with open('test2.json','w+') as file:
     for d in [d1,d2]:
             list1 = []
             list1.append(d1)
             list1.append(d2)
             json.dump(list1,file)

Comments

0

Try this

d1 = {"a":1}
d2 = {"b":2}
import json
with open('test2.json','w+') as file:
    json.dump([d1,d2],file)

Comments

0

A list of dictionaries is a json serializable ofject already, so just serialize the whole object you need:

import json
with open('test2.json','w+') as file:
    json.dump([{"a":1}, {"b":2}],file)

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.