Introduction
JSON or JavaScript Object Notation is a file format to store data in human readable format. It stores data as key value pair, where the key needs to be unique but the value can of any type which json can serialize. They popularity of JSON arises from the fact that it replicates the dictionary structure which is very common in most languages like python. The json module comes inbuilt in python and can be imported as -
import json
#or
from json import *
Functions
The JSON module in python has only two major functions (4 in total but functions like dump/dumps and load/loads show similar behaviour)
1. Dumps - It serializes a dictionary object into a json style string.
2. Loads - It deserializes a json type string into file to a dictionary object.
Dumps
Syntax -
dumps(dict_obj)
Example -
import json
handle = open('data.json','w')
data = {
"hello":123,
456:"world",
"welcome":
"cppsecrets.com",
12:43
}
jsonString = json.dumps(data)
handle.write(jsonString)
handle.close()
Output -
Loads
Syntax -
loads(json_string)
Example -
import json
with open('data.json','r') as handle:
jsonString = handle.read()
jsonData = json.loads(jsonString)
print(jsonData)
Output -
.
Comments