JSON Handling in Python

JSON (JavaScript Object Notation)

How to read a JSON file:

Python has built-in functions to read, parse, and write JSON files. By using the .load() function, we can read a JSON file.


Import json

with open('input.json','r') as inputjsonfile:

    inputjson = json.load(inputjsonfile)        


How to read values in a JSON file:

JSON is always constructed with a key-value pair. Every value has one key, so by calling the key, we can access values.

Read dictionary values:

Sample:

{

“Name”:”abc”

 }


Import json

with open('input.json','r') as inputjsonfile:

	inputjson = json.load(inputjsonfile)

	for key in inputjson.keys():

		print(inputjson[key])        

Read nested dictionary values:

Sample:

{

“Name”:”abc”,

“Address”:{

“Street”:”first street”

}

 }


Import json

with open('input.json','r') as inputjsonfile:

	inputjson = json.load(inputjsonfile)

	for key in inputjson.keys():

		print(inputjson[key])

		for nestedkey in inputjson[key].keys():

			print(inputjson[key][nestedkey])        

Read the list of dictionary values:

For a list of dictionaries, first we have to call the list number, and then we can access the dictionary the same way we did for reading dictionaries.

Sample:

{

“Name”:”abc”,

“Address”:[

“Address1”:{

“Street”:”first street”

},

“Address2”:{

“Street”:”second street”

}

]

 }


Import json

with open('input.json','r') as inputjsonfile:

	inputjson = json.load(inputjsonfile)

	for key in inputjson.keys():

		print(inputjson[key])

		for n in range(0, len(inputjson[key]):

			for nestedkey in inputjson[key][n].keys():

				print(inputjson[key][n][nestedkey])        

How to write a JSON file:

By using the .dump() function, we can write a JSON file.


Import json

with open('input.json','r') as inputjsonfile:

	inputjson = json.load(inputjsonfile)

	Outputjson = inputjson 

with open('output.json','w') as outputjsonfile

	json.dump(Outputjson , outputjsonfile)        

How to write pretty json:


Import json

with open('input.json','r') as inputjsonfile:

	inputjson = json.load(inputjsonfile)

	Outputjson = inputjson 

with open('output.json','w') as outputjsonfile

	json.dump(Outputjson , outputjsonfile, indent=3)        

To view or add a comment, sign in

More articles by Rajadurai Ramasamy

Explore content categories