You are currently viewing Convert JSON to Dictionary in Python

Let’s discuss how to convert the JSON string object to a Dictionary in python. From JSON string, we can convert it to a dictionary using the json.loads() method. Suppose you have a JSON file, then loads() will not work. In this scenario, we can use json.load() method (load without s at the end).

Advertisements

JSON stands for Javascript object notation which is mostly used to serialize structured data and exchange it over web applications. Python has a built-in package called json to work with JSON file or strings. The data in the JSON is made up of the form of key/value pairs and they can be enclosed with {}. Look wise it is similar to a Python dictionary. But JSON keys must be string-type objects with a double-quoted and values can be any datatype such as string, integer, nested JSON, a list, a tuple, or even another dictionary. 

1. Quick Examples of Converting JSON to a Dictionary

If you are in a hurry, below are some quick examples of converting JSON to a Dictionary (dict).


# Quick examples of converting JSON to a dictionary

# Import json module
import json

# Method 1 : Using json.loads() 
# To convert json to dictionary
country_dict1 = json.loads(country_json)
print(country_dict1)

# Method 2 : Nested dictionary
# Using json.loads() 
country_dict2 = json.loads(country_json)
print(country_dict2)

# Method 3 : Using json.load()
with open('country1.json') as country_json1:
  country_dict = json.load(country_json1)
  print(country_dict)
  print(type(country_dict))

# Method 4 : Nested dictionary
# Using json.load()
with open('country1.json') as country_json1:
  country_dict = json.load(country_json1)
  print(country_dict['Country Name'])
  print(country_dict['States'])
  print(country_dict['Lakes_Available'])

2. Use json.loads() to Convert JSON String to Dictionary

To convert JSON string to a Python dictionary object you can use the json.loads(), this method parses the JSON string and converts it into the dictionary. This method is available in the json module, so you need to import it to use this module.

This method accepts the json string as a parameter and converts this json string into a dictionary object, the string has to be in dictionary format otherwise you may get an error.

2.1 Syntax of json.loads()

Following is the syntax of json.loads() method.


# Syntax
json.loads(input_json)

Here, input_json is the string object that holds the JSON.

2.2 Convert JSON String to Dictionary Examples

Let’s have a JSON string that holds country details and convert this into a dictionary. First, import the json module as we will be using the loads() function.


# Import json module
import json

# Initialize the json string
country_json = '{"Country Name": "USA","States": ["Ohio", "Texas","California"],"Lakes_Available":"Yes"}'

# Using json.loads()
country_dict = json.loads(country_json)
print("Converting json to dictionary:\n",country_dict)
print("Data type",type(country_dict))

Yields below output.

python convert json dictionary

For confirmation, we used the type() function to check whether the json is converted to a dictionary or not. Here, we can see that country_json is converted to the dictionary.

2.3 Convert Nested JSON to Dictionary

In the previous example, the string is similar to the dictionary but in this example, we will consider the json as nested and convert this into a nested dictionary.


# Import json module
import json

# Initialize json
country_json = '{ "Country Name": "USA","States": {"Ohio":52343, "Texas":44554,"California":21233},"Crops":{"Crop 1:":["Maize","tobacco","wheat"],"Crop 2:":["Paddy","Chillies"]}}'

# Using json.loads()
country_dict = json.loads(country_json)
print(country_dict)
print(type(country_dict))

# Output:
# {'Country Name': 'USA', 'States': {'Ohio': 52343, 'Texas': 44554, 'California': 21233}, 
'Crops': {'Crop 1:': ['Maize', 'tobacco', 'wheat'], 'Crop 2:': ['Paddy', 'Chillies']}}

Here, ‘States‘ holds again a dictionary as value.

3. Using json.load()

The above examples cover when you have a JSON string, but, If you are having a JSON file that you need to convert into a Python dictionary, you can use the json.load() method. It will parse the json string and convert it into the dictionary.

This method accepts JSON objects as a parameter. This JSON object is like a file pointer that will come from the json file. Let’s first see the syntax and them some examples of using this method.

3.1 Syntax of json.load()

Following is the syntax of json.load() method.


# Syntax of json.load()
json.load(input_json)

3.2 Examples

Example 1: Let’s have a JSON string that holds country details and convert this into a dictionary. By using open() method, we will get the data present in the JSON file.


# Import json module
import json

# Using json.load()
with open('country1.json') as country_json1:
  country_dict = json.load(country_json1)
  print(country_dict)

# Output:
# {'Country Name': 'USA', 'States': ['Ohio', 'Texas', 'California'], 'Lakes_Available': 'Yes'}

Example 2: It can also be possible to return a particular value based on the key after converting JSON to the dictionary. Let’s return the ‘Country Name’, ‘States’, and ‘Lakes_Available’ separately.


# Import json module
import json

# Using json.load()
with open('country1.json') as country_json1:
  country_dict = json.load(country_json1)
  print(country_dict['Country Name'])
  print(country_dict['States'])
  print(country_dict['Lakes_Available'])

# Output:
# India
# ['Ohio', 'Texas', 'California']
# Yes

Example 3: Load ‘country2.json’ and convert it into a dictionary and use the keys to return associated values.


# Import json module
import json

# Using json.load()
with open('country2.json') as country_json2:
  country_dict = json.load(country_json2)
  print(country_dict,"\n")
  print(country_dict['States'])
  print(country_dict['States']['AP'])
  print(country_dict['Crops'])
  print(country_dict['Crops']['Crop 2:'])

# Output:
# {'Country Name': 'India', 'States': {'Florida': 52343, 'Texas': 44554, 'Ohio': 21233}, 'Crops': {'Crop 1:': ['Maize', 'tobacco', 'wheat'], 'Crop 2:': ['Paddy', 'Chillies']}} 

# {'Florida': 52343, 'Texas': 44554, 'Ohio': 21233}
# 52343
# {'Crop 1:': ['Maize', 'tobacco', 'wheat'], 'Crop 2:': ['Paddy', 'Chillies']}
# ['Paddy', 'Chillies']

4. Difference between json.load() and json.loads()

Let’s see the difference between json.load() and json.loads().


json.load()
json.loads()
json.load() will take a file object and return the JSON object.json.loads() method takes a JSON string and parses it
It deserializes a file.It deserializes a native string, byte, or byte array.

Frequently Asked Questions on Convert JSON to Dictionary in Python

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is commonly used to transmit data between a server and a web application, as well as to store and exchange data.

How can I convert a JSON string to a Python dictionary in Python?

You can convert a JSON string to a Python dictionary in Python using the json module. The json.loads() function is specifically designed for this purpose. For example, json_string is the JSON data in string format. The json.loads() function parses the JSON string and converts it into a Python dictionary (python_dict).

Why do we need to convert JSON to a dictionary in Python?

JSON is often used to represent structured data, and converting it to a dictionary in Python allows you to work with the data in a more convenient and flexible way. Python dictionaries are a native data type that can be easily manipulated, searched, and modified.

What happens if the JSON string is not well-formed?

If the JSON string is not well-formed, i.e., it contains syntax errors, attempting to load it using json.loads() will raise a json.JSONDecodeError. It’s important to handle such exceptions appropriately in your code.

How can I convert a JSON string to a dictionary in Python?

You can use the json.loads() function from the json module in Python. This function parses a JSON string and returns a Python object, typically a dictionary.

Can I convert a Python dictionary back to a JSON string?

You can convert a Python dictionary back to a JSON string using the json.dumps() function in Python. For example, python_dict is a Python dictionary, and json.dumps() serializes it into a JSON-formatted string (json_string). The resulting JSON string can be used for various purposes, such as storing data in a file or sending it over a network.

Conclusion

In this article, you have learned how to convert JSON string to a dictionary and JSON file to a dictionary object using json.loads() and json.load() method respectively. We utilized the type() function to check whether the JSON is converted to a dictionary or not. Finally, we discussed the differences between json.load() and json.loads().