Appending JSON file through python code

后端 未结 2 529
春和景丽
春和景丽 2021-01-15 17:27

I\'m trying to create a function that would append data into json file follow with same indentation which is already exist. I created json file as given below.



        
相关标签:
2条回答
  • 2021-01-15 17:57

    Instead of appending only one line, you can also choose to write the whole json again.

    with open('TableA.json') as data_file:    
        data = json.load(data_file)
    a_dict = {"ID": "10005", "Name": "Manoj","Age": "31"}
    new_data = data["TableA"].append(a_dict)
    with open('TableA.json','w') as f:
        f.write(json.dumps(new_data, indent=4, sort_keys=True))
    
    0 讨论(0)
  • 2021-01-15 18:00

    I made some changes for get proper output. If someone help me to optimize the code then please help for this.

    import json
    
    # Write Data
    a_dict = {}
    try:
        with open('TableA.json') as data_file:    
            data = json.load(data_file)
            temp_list = []
            for dicObj in data["TableA"]:
                temp_list.append(dicObj)
            temp_list.append({"ID": "10006", "Name": "Ritesh","Age": "21"})
            data["TableA"] = temp_list
            a_dict["TableA"] = data["TableA"]
            with open('TableA.json','w') as f:
                f.write(json.dumps(a_dict, indent=4, sort_keys=True, encoding="utf-8"))
    except IOError as io:
        print "ERROR: ", io
    
    # Read data from Json File
    with open('TableA.json') as data_file:    
        data = json.load(data_file)
    
    for i in data["TableA"]:
        print "ID: \t", i["ID"]
        print "Name: \t", i["Name"]
        print "Age: \t", i["Age"]
    

    Output:

     {
        "TableA": [
            {
                "Age": "29", 
                "ID": "10001", 
                "Name": "Chandan"
            }, 
            {
                "Age": "24", 
                "ID": "10002", 
                "Name": "Rajesh"
            }, 
            {
                "Age": "25", 
                "ID": "10003", 
                "Name": "Raju"
            }, 
            {
                "Age": "31", 
                "ID": "10005", 
                "Name": "Manoj"
            }, 
            {
                "Age": "21", 
                "ID": "10004", 
                "Name": "Ritesh"
            }, 
            {
                "Age": "21", 
                "ID": "10006", 
                "Name": "Ritesh"
            }
        ]
    }
    
    0 讨论(0)
提交回复
热议问题