2

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 ?

3 Answers 3

2

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

Comments

2

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)

1 Comment

Thanks all for your prompt answers.
0

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)

2 Comments

I accidentally edited your answer, Sorry. Rollbacked.
It is alright. An accident is an accident.

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.