ilexcel
ilexcel

Reputation: 977

Write a single JSON from multiple dictionaries

I am trying to write multiple may be 20 dictionaries into a single json file by appending/dumping one by one onto a JSON file, So far I've done the below code to accomplish but i can't. help if someone know better approach

run1 = client.send_get('get_tests/11023')
run2 = client.send_get('get_tests/11038')

with open('result.json', 'w') as fp:
    json.dump(run1, fp)

Upvotes: 2

Views: 3495

Answers (2)

Mostafa Babaii
Mostafa Babaii

Reputation: 158

Try this:

run1 = client.send_get('get_tests/11023')
run2 = client.send_get('get_tests/11038')

with open('result.json', 'w') as fp:
    json.dumps({'run1': run1, 'run2': run2}, fp)

If you want to push just single dict in file, you have to merge run1 and run2:

run1.update(run2)

Then try:

with open('result.json', 'w') as fp:
    json.dumps(run1, fp)

Also you can try this:

with open('result.json', 'w') as fp:
    json.dumps({**run1, **run2}, fp)

Upvotes: 3

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72755

I'm not sure this is possible. What do you expect when you read the contents of the file back?

When you read something out of a file, it should be valid json for it to load. One option is to create a dictionary like so

d = dict(run1 = run1, run2 = run2, ... )

and then json.dump d itself into the file.

Update: Here is an example. This uses a list instead of a dictionary (based on your comment) but the idea is the same.

run1 = dict(status = "ok", message = "All good")
run2 = dict(status = "error", message = "Couldn't connect")

def save_data(*runs):
   with open("foo.json", "w") as f:
      json.dump(list(runs), f)

def load_data(fname):
   with open(fname) as f:
      return json.load(f)


save_data(run1, run2)
outputs = load_data("foo.json")
print (outputs)

[{'status': 'ok', 'message': 'All good'}, {'status': 'error', 'message': "Couldn't connect"}]

Upvotes: 3

Related Questions