Python json.loads() Method Tutorial

JSON or JavaScript Object Notation is an object type that is used to exchange data between client and server or different hosts. JSON provides easy to read and parse structure that is also human-readable. Python provides the json module with different functions in order to work with JSON data. The json.loads() function is used to load and parse provided text as a JSON object.

json.loads() Method Syntax

The json.loads() method has the following syntax. This method returns a Python dictionary. The Python dictionary is very similar to the JSON object.

json.loads(STRING)
  • STRING is the JSON text which will be converted into a JSON object or dictionary which is easy to work with.

Load String as JSON Object

The json.loads() method is provided via the json module and as expected it should be imported with the import json statement. The JSON string is stored inside the str . Alternatively, the JSON string can be read from a file.

import json

str = """{
      "Name":"İsmail Baydan",
      "Age":38,
      "Locations":["Ankara","Canakkale"]
      }"""


d = json.loads(str)

print(d)

From the output, we can see that the returned object is a dictionary with some string, integer, or list.

{'Name': 'İsmail Baydan', 'Age': 38, 'Locations': ['Ankara', 'Canakkale']}

Use JSON Object

The JSON object is stored as dictionary type and values can be stored as a string, integer, and list. By using dictionary keys the JSON object can be easily used. The Locations is a list which items can be accessed by using [] brackets with index numbers of the items.

import json

str = """{
      "Name":"İsmail Baydan",
      "Age":38,
      "Locations":["Ankara","Canakkale","İzmir"]
      }"""


d = json.loads(str)

print(d["Name"])

print(d["Locations"][0])

print(d["Locations"][1])

print(d["Locations"][2])
İsmail Baydan
Ankara
Canakkale
İzmir

Leave a Comment