In python read json file is very easy. In this article we will explain how to read a JSON file from the disk and use it in python.

What is JSON?
JSON is a data exchange format used all over the internet. JSON (JavaScript Object Notation) can be used by all high level programming languages.

How to use JSON with python?
The way this works is by first having a json file on your disk.
The program then loads the file for parsing, parses it and then you can use it.

Related course: Complete Python Programming Course & Exercises

python read json

JSON file

Create a file on your disk (name it: example.json). The python program below reads the json file and uses the values directly.

The file can contain a one liner. The file content of example.json is:

1
{"usd":1,"eur":1.2,"gbp": 1.2}

Save the file to example.json.

python Example

Then create the program below and run it.:

1
2
3
4
5
6
7
8
9
10
11
12
13
import json

# read file
with open('example.json', 'r') as myfile:
data=myfile.read()

# parse file
obj = json.loads(data)

# show values
print("usd: " + str(obj['usd']))
print("eur: " + str(obj['eur']))
print("gbp: " + str(obj['gbp']))

The above program will open the file ‘example.json’ and parse it. You can access the JSON data like any variables.