DEV Community

Michael Butak
Michael Butak

Posted on • Updated on

Handling JSON in Python

You might wonder, "json.load, json.loads, json.dump, json.dumps oh my!" Which do I use for which situation?

json.load
<- you want to read a json file and access its contents as a python object. Example:

You have a file named 'some-json.json' which is a dict with properties "A" and "B". In python you could access it this way:

import json
some_dict = json.load(open("some-json.json", "r"))

print(f"Property 'A' is {some_dict['A']}")
print(f"Property 'B' is {some_dict['B']}")
Enter fullscreen mode Exit fullscreen mode

json.loads
<- you want to convert a json string into a python object. Example:

You have a string like:

some-json-string = ‘{“A”: “BOB”, ”B”: “JOHN”, “C”: “SAM”}’
Enter fullscreen mode Exit fullscreen mode

And you wish to access its properties. You could do it with json.loads (where the 's' stands for string):

import json
some-json-string = ‘{“A”: “BOB”, ”B”: “JOHN”, “C”: “SAM”}’
some_dict = json.loads(some-json-string)
print(f"Property 'A' is {some_dict['A']}")
print(f"Property 'B' is {some_dict['B']}")
Enter fullscreen mode Exit fullscreen mode

json.dumps
Next we have json.dumps, which allows us to make a json string (hence the 's' in 'dumps') out of a python object. An example:

import json
some_dict = {
    'A': 1,
    'B': 2,
}

serialized-json-ready-to-send = json.dumps(some_dict)
Enter fullscreen mode Exit fullscreen mode

json.dump
Last we have json.dump, which is used to write python to a json file. Example:

import json

# content to write to json file:
some_dict = {
    'A': 1,
    'B': 2,
}

with open("output.json", "w") as outfile:
    json.dump(some_dict, outfile)

Enter fullscreen mode Exit fullscreen mode

Top comments (0)