
Read and write json file in python
Json file format is commonly used in most of the programming languages to store data or exchange the data between back end and front end, or between different applications and systems. In this article, I will be explaining how to read and write json file in python programming language.
Read from a JSON file
Python has a json module which makes the read and write json pretty easy. First, let’s assume we have the below example.json file to be read.
{ "link": "www.codeforests.com", "name": "ken", "member": true, "hobbies": ["jogging", "watching movie"] }
To read the file, we can simply use the load method and pass in the file descriptor.
example = json.load(open("example.json"))
Now you can access the example dictionary for the data, e.g.
print(config["hobbies"])
The output would be :
['jogging', 'watching movie']
Write into JSON file
Let’s continue to use the previous example, and try to add one more hobby into the hobbies. Then save the json object into a file.
This time, you can use the json.dump and pass in the file descriptor to be written to:
example["hobbies"].append("badminton") with open("example.json", "w") as f: json.dump(example, f)
If you look at the json documentation, there are two more methods : json.loads and json.dumps. The main difference of this two methods vs json.load & json.dumps is that the loads and dumps take the str representation of the json object. e.g.:
obj = json.loads('{"json":"obj"}') print(obj) print(json.dumps({"json":"obj"}))