Ruan Bekker's Blog

From a Curious mind to Posts on Github

How to Read and Write Json Data With Python

This is a short tutorial on how to use python to write and read files.

Example

To write the following json data:

1
{"name": "ruan"}

To a file named /tmp/data.json, we will be using this code:

1
2
3
4
5
import json

data = {"name": "ruan"}
with open('data.json', 'w') as f:
    f.write(json.dumps(data))

When we execute that code, we will find the data inside that file:

1
2
$ cat /tmp/data.json
{"name": "ruan"}

And if we want to use python to read the data:

1
2
3
4
import json

with open('data.json', 'r') as f:
    json.loads(f.read())

When we execute that code, we will see:

1
{'name': 'ruan'}

Thank You

Thanks for reading, feel free to check out my website, read my newsletter or follow me at @ruanbekker on Twitter.