How to use the "json" Module in Python

How to use the "json" Module in Python

Overview

This article will explain what JSON is and how to use the "json" module in Python to convert a string data type to a dictionary data type and convert a dictionary data type to a string data type.

Materials

  • Computer

  • Python

    • Modules used: json
  • Terminal, Shell or IDE

What is JSON

JSON stands for Javascript object notation. (1) This format of text is used to contain and save a lot of information that can be analyzed for future use. JSON's data type is a dictionary which makes it useful for storing a lot of information.

Why use the Python "json" Module

The "json" module is useful for converting string data type variables to dictionary data type variables and converting dictionary data type variables to string data type variables.

How to use the "json" Module

Converting a String to a Dictionary

The json method "json.loads()" converts a string to a dictionary.

import json

a_string = '{"planet":"Earth", "animal":["cat", "dog"], "numbers":{"One":1, "Two":2}}'

change_string_to_dictionary = json.loads(a_string)

print(type(change_string_to_dictionary))
print(change_string_to_dictionary["planet"])
print(change_string_to_dictionary["animal"][0])
print(change_string_to_dictionary["numbers"]["One"])

Converting a Dictionary to a String

The json method "json.dumps()" converts a dictionary to a string.

import json

a_dictionary = {"first_key": 13, "second_key": ["sample_text", 15]}
change_dictionary_to_string = json.dumps(a_dictionary)
print(type(change_dictionary_to_string))
print(change_dictionary_to_string)

Printing all the Keys and Values from a Dictionary

By using a for-loop, it is also possible to print all the keys and values from a Dictionary.

import json

a_string = '{"planet":"Earth", "animal":["cat", "dog"], "numbers":{"One":1, "Two":2}}'

change_string_to_dictionary = json.loads(a_string)

for key in change_string_to_dictionary:
    print(key) #Prints all keys
    print(change_string_to_dictionary[key]) #Prints all values

Sources

https://www.w3schools.com/python/python_json.asp (1)

Source Code

https://github.com/AndrewDass1/TUTORIALS-AND-NOTES/tree/main/Python/JSON/Intro%20to%20using%20the%20JSON%20Module