How to use JSON files in Python

The json package in Python lets us work with JavaScript Object Notation (JSON). We can also use it to convert any Python object into JSON data.

To do this, we need to import the JavaScript Object Notationjson package at the start of the program we want to write.

Required library


import json

There are two major use-cases of JSON in Python:

  • Converting a JSON string to a Python dictionary
  • Converting a Python object to JSON

Let's see discuss both in detail.

Converting a JSON string to a Python Dictionary

The json.loads() function converts or retrieves the components of the JSON string into the dictionary.

Syntax

json.loads(str String)

Example

In this example, we parse a JSON string into a Python dictionary.

import json
# JSON string
myjson = '{ "student name":"Fahad Sajid", "class":"Purple", "Distinction":"House Caption"}'
# Parsing the JSON string
mydict = json.loads(myjson)
print(mydict["Distinction"])
print(mydict["class"])
  • Line 1: We import the json package.
  • Line 3: We define a JSON string named myjson. We use this name to access the string.
  • Line 5: We call the json.loads(myjson) function. This loads the JSON string in the Python dictionary, which is represented by mydict.
  • Line 6: We print out the Distinction value from mydict. By using this function, we can filter any part of the string.
  • Line 7: We display the class using the same resolution operator ([]).

Converting a Python object to JSON

The json.dumps() function converts any Python object into a JSON string.

Syntax


json.dumps(Python_obj)

Example

In this example, we convert a Python dictionary into a JSON format.

import json
# Dictionary object
python_obj = {
"Student_name":"Michael Linda",
"Class":"Green",
"Marks":80,
"Distinction":"Random"}
# Invoking the json.dump() method
newjson = json.dumps(python_obj)
print(newjson)
  • Line 1: We import the json package.
  • Line 3: We define the Python dictionary python_obj.
  • Line 9: We call the json.dumps(python_obj) function. This sends the ython object to the JSON string. newjson represents the new JSON string we generate.
  • Line 10: We print out the new JSON string.

Free Resources