how to dump string(list of dictionaries) as json object in python

Question:

I have item data in array of dictionary in python.

items = [{'key': {'Brand': 'Tesla', 'Date': '2020'}, 'Total': 56, 'my_vin': '#468123'},
            {'key': {'Brand': 'Toyota', 'Date': '2022'}, 'Total': 6, 'my_vin': '#468210'},
            {'key': {'Brand': 'Audi', 'Date': '2023'}, 'Total': 1, 'my_vin': '#468132'}]

I want to re-format this data and dump into json format. and I’m able to do that.

import json
with open('new_json.json', 'w') as njs:
    for i in items:
        format_data = {'only_brand': i['key']['Brand'], 'only_date': i['key']['Date']}
        print(format_data)

        json.dump(format_data, njs, indent=4)

enter image description here
But when I tried read json file it gives format error

with open('new_json.json', 'r') as f:
    data = json.loads(f.read())
    print(data)

json.decoder.JSONDecodeError: Extra data: line 4 column 2 (char 54)

I’m not sure this is the right way to do what I want to do and I have to loop through very long items in a real case. How can I get a proper json document ?

Asked By: Alexander

||

Answers:

You can’t write multiple JSON objects to the file. Put all the dictionaries in a list, and write that once.

import json
with open('new_json.json', 'w') as njs:
    format_data = [{'only_brand': i['key']['Brand'], 'only_date': i['key']['Date']} for i in items]
    print(format_data)

    json.dump(format_data, njs, indent=4)
Answered By: Barmar

You need to dump the whole list at once, not individual items:

import json

output = [
    {'only_brand': i['key']['Brand'], 'only_date': i['key']['Date']}
    for i in items
]

with open('new_json.json', 'w') as njs:
        json.dump(output, njs, indent=4)
Answered By: Hai Vu

You can do like this,

import json
with open('new_json.json', 'w') as njs:
    new_dict = [{"only_brand": i["key"]["Brand"], "only_date": i["key"]["Date"]} for i in items]
    json.dump(new_dict, njs, indent=4)
Answered By: Rahul K P
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.