Python JSON Append to JSON file using Python [Updating a JSON file.]














































Python JSON Append to JSON file using Python [Updating a JSON file.]



Append to JSON file using Python  [Updating a JSON file.]


 Functions Used:
  • json.loads(): json.loads() function is present in python built-in json module. This function is used to parse the JSON string.

    Syntax: json.loads(json_string)

    Parameter: It takes JSON string as the parameter.

    Return type: It returns the python dictionary object.


  • json.dumps(): json.dumps() function is present in python built-in json module. This function is used to convert Python object into JSON string.

    Syntax: json.dumps(object)

    Parameter: It takes Python Object as the parameter.

    Return type: It returns the JSON string.

  • update(): This method update the dictionary with elements from another dictionary object or from an iterable key/value pair.

    Syntax: dict.update([other])

    Parameters: Takes another dicitonary or an iterable key/value pair.

    Return type: Returns None.

Updating a JSON file. 

Suppose the json file looks like this:
{
"emp_details":[
{"name": "Bob",
"languages": "English"}
]
}

We want to add another json data after emp_details. Below is the implementation.

Python code:
import json 


# function to add to JSON
def write_json(data, filename='emp.json'):
with open(filename,'w') as f:
json.dump(data, f, indent=2)


with open('emp.json') as json_file:
data = json.load(json_file)

temp = data['emp_details']

# python object to be appended
y = '{"name": "madhu", "languages": "Hindi"}'



# appending data to emp_details
temp.append(y)

write_json(data)

output:
{
"emp_details": [
{
"name": "Bob",
"languages": "English"
},

{"name":"madhu",
"languages": "Hindi"}
]
}


Comments