DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป

DEV Community ๐Ÿ‘ฉโ€๐Ÿ’ป๐Ÿ‘จโ€๐Ÿ’ป is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
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)

๐ŸŒš Friends don't let friends browse without dark mode.

Sorry, it's true.