2

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.

{
    "TableA":
        [
            {"ID": "10001", "Name": "Chandan","Age": "29"},
            {"ID": "10002", "Name": "Rajesh", "Age": "24"},
            {"ID": "10003", "Name": "Raju", "Age": "25"}
        ]
}

Python Code:

import json

# Write Data on Json file
a_dict = {"ID": "10005", "Name": "Manoj","Age": "31"}
try:
    with open('TableA.json', 'a') as f:
        json_obj = json.dump(a_dict, json.load(f),ensure_ascii=False)
        f.write(json_obj)
        f.close()
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"]
3
  • Do you have a question? If you have a particular problem with the Python code you are using, then (1) tag the question with python, (2) provide the relevant piece of code, and (3) describe the particular problem you bump into. Also provide an example with input and expected output. Commented May 9, 2017 at 12:04
  • Even after your edit your question is pretty ambiguous. I'm voting to close. Try to clarify what you mean by same indentation by givings example input AND output, and what is wrong with the ouput your code produces. Commented May 9, 2017 at 12:51
  • #Rick, Actually when I am going to read JSON file which updated through my code and then I am getting error as JSON is not valid format. So I focus on indentation. Please look on this and give me some ideas. Commented May 10, 2017 at 5:03

2 Answers 2

2

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

Comments

1

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))

1 Comment

#Thanks! #iamkhush, your code is useful to get my proper output but I made changes little bit to make it more clear.

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.