Encoding and Decoding JSON with Python — A Cheatsheet

Sisay A. Chala
2 min readNov 19, 2020
JSON and Python — A Cheatsheet

Conversion of json string (or json file) to python and vice versa is often a confusing endeavor. This article can serve as a cheatsheet.

In this short post, I provide a highlight of the conversion functions from json to python and vice versa. The functions are:

  • json.loads(jsonString) — json string to python object
  • json.dumps(pythonObject) — python object to json string
  • json.load(fileHandler) — json file to python object — python object from file
  • json.dump(jsonString or pythonObject, fileHandler) — json string or python object to json file

When you want to access json elements using their keys, you need to convert a json string or a json file into a python dictionary with json.loads(json string) or json.dumps(file handler), respectively. Note the s in loads — which perhaps stands for string, thus loads == loadString.

Similarly, when you want to convert a python dictionary to a json string, e.g., for string processing, or want to save it as a json file, you use json.load(python_dict) or json.dump(json string or python object, file handler), respectively. The following code snippets demonstrates these functions. But first of all, you need to import the required library, i.e., json.

import json
  1. json.loads()
json_string = '{"name": "John Due", "ID": 123456}'

#print(json_string["name"]) #TypeError: string indices must be integers

json_dict = json.loads(json_string)
#type(json_string) # <class 'str'>
#type(json_dict) # <class 'dict'>
print(json_dict["name"])

the above code produces:

John Due

2. json.dumps()

json_string_1 = json.dumps(json_dict, indent=5)

#print("Json_dict" + json_dict) #TypeError: can only concatenate str (not "dict") to str
#type(json_string_1) # <class 'str'>
print(json_string_1)

the above code snippet produces:

{
"name": "John Due",
"ID": 123456
}

3. json.dump()

# writes in file a json string: "{\"name\": \"John Due\", \"ID\": 123456}"
with
open("json_file.json", "w") as json_file:
json.dump(json_string, json_file)
# writes in file a json object: {"name": "John Due", "ID": 123456}
with open("json_file1.json", "w") as json_file1:
json.dump(json_dict, json_file1)

4. json.load()

with open("json_file.json", "r") as json_file:
file_content = json.load(json_file)

#type(file_content) # <class 'str'>
print(file_content)

with open("json_file1.json", "r") as json_file1:
file_content_1 = json.load(json_file1)

#type(file_content_1) # <class 'dict'>
print(file_content_1)

The above code snippet produces

{"name": "John Due", "ID": 123456}
{'name': 'John Due', 'ID': 123456}

I hope this article give a summary of the four functions that are often used for encoding and decoding json data. Drop me a question or feedback, if you have one, in the comment section.

--

--