0

I'm working on a json file and I modified it by the following code:

import json


def json_to_dict(obj, key):
    _dict = {}        
    if type(obj) is dict:
        for key in obj.keys():
            _dict[key] = json_to_dict(obj[key], key)
        return _dict
    if type(obj) is list:
        for idx, child_obj in enumerate(obj):
            _dict[f"{key}{idx}"] = json_to_dict(child_obj, key)
        return _dict
    return obj

with open('data.json', 'r',encoding="utf-8") as f:
    read_data = f.read()
    products = []
    for idx, product in enumerate(json.loads(read_data)):
        products.append(json_to_dict(product, idx))
    
    print(json.dumps(products, indent=4, sort_keys=True))
    json.dump(products,f,indent=4, sort_keys=True))
        
f.closed

The result of print(json.dumps(products, indent=4, sort_keys=True)) is the result I want. But I fail on saving the data to the original json file( data.json) by using json.dump(products,f,indent=4, sort_keys=True)) How can I change to code to save the result correctly?

kali
  • 79
  • 5
  • ``But I fail [...]`` please always include the full error stack in your question in such a case, it helps us to help you. – Mike Scotty Jul 12 '21 at 08:28

0 Answers0