Using json.loads()
To easily convert an input JSON string to a dictionary, use the json.loads() method in Python.
Let’s take a new string that consists of JSON data and convert it into a dictionary, and then verify the data type using the type() method.
import json json_string = '{"student_name": "Smith", "age": 15, "country": "USA"}' # Convert JSON string to dictionary dict = json.loads(json_string) print(dict) # Output: {'student_name': 'Smith', 'age': 15, 'country': 'USA'} print(type(dict)) # Output: <class 'dict'>
Nested JSON string
What if the string contains nested json data? Well, it will return a nested dictionary.
import json json_string = '{"student_name": "Smith", "personal_info": {"age": 15, "country": "USA"}}' dict = json.loads(json_string) print(dict) # Output: {'student_name': 'Smith', 'personal_info': {'age': 15, 'country': 'USA'}} print(type(dict)) # Output: <class 'dict'>
Handling JSON Arrays
If your input is a nested array (list of objects), Python will convert it to a list of dictionaries.
import json # JSON array json_string = '''[ {"id": 1, "name": "Krunal"}, {"id": 2, "name": "Ankit"} ]''' # Convert to list of dictionaries dictionary = json.loads(json_string) # Access data print(dictionary[0]['name']) # Output: Krunal print(dictionary[1]['id']) # Output: 2
You can see from the above output that each element in the list can be a dictionary, allowing iteration or indexed access.
Converting JSON from an API Response
When you fetch the JSON from an API, you can use the “requests” module to get the JSON string and parse it. The requests library’s .json() method internally uses json.loads() method to convert the API’s JSON response to a dictionary.
import requests # Example API (public API for testing) response = requests.get('https://jsonplaceholder.typicode.com/users/5') json_data = response.json() # Automatically parses JSON to dictionary # Accessing data print(json_data['name']) # Output: Chelsey Dietrich
Invalid JSON
If the input JSON string has a syntax error, it will raise a json.JSONDecodeError.
import json # Invalid JSON (missing quotes around key) json_string = '{name: "Krunal", "age": 32}' try: dictionary = json.loads(json_string) except json.JSONDecodeError as e: print(f"Error: {e}") # Output: Error: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Empty or Null JSON
What if an input is an empty JSON or contains Null values? An empty json string will return an empty json, and a JSON of null will return None.
import json # Empty JSON object json_string = '{}' dictionary = json.loads(json_string) print(dictionary) # Output: {} # JSON with null json_string = '{"name": null, "age": 30}' dictionary = json.loads(json_string) print(dictionary['name']) # Output: None
Unicode and special characters
JSON data often contains special characters in real-life scenarios. Python handles special and unicode characters automatically if they are in the input json data.
import json # JSON with Unicode json_string = '{"name": "José", "city": "São Paulo"}' dictionary = json.loads(json_string) print(dictionary['name']) # Output: José
Handling missing keys
What if your input data contains missing keys in JSON? If you convert it to a dictionary, it may raise a KeyError.
To handle the potential error, we can use the dict.get() method. The dict.get(key, default) method returns the value if key exists; otherwise, returns default. This prevents KeyError.
import json json_string = '{"name": "Krunal", "age": 30, "city": "New York"}' dict = json.loads(json_string) # Handle missing keys safely using .get() with a default value print(dict.get('age', 0)) # Output: 30 (existing key) print(dict.get('salary', 0)) # Output: 0 (missing key, default used)
In the case of the “salary” key, it does not exist; however, we have already passed the default value, which is 0. So, the output is 0, even if the key is missing. So, it handled the potential error.
Using json.load()
If your input is a file, you can load it using json.load() method.
The built-in JSON module function json.load() method reads a JSON data directly from a file.
import json # Open the JSON file for reading with open('data.json') as file: # Use json.load() to read the file and convert it to a dictionary dict = json.load(file) print(dict) # Output: {'student_name': 'Smith', 'age': 22, 'country': 'USA'} print(type(dict)) # Output: <class 'dict'>
Nested JSON File
What if the file contains nested json data? Well, let’s find out.
Below is the nested_data.json file.
import json # Open the Nested JSON file for reading with open('nested_data.json') as file: # Use json.load() to read the file and convert it to a dictionary dict = json.load(file) print(dict) # Output: {'student_name': 'Smith', 'personal_info': {'age': 22, 'country': 'USA'}} print(type(dict)) # Output: <class 'dict'>
That’s it.