JSON is a vastly used human-readable and machine-friendly data format that facilitates cross-platform data exchange in various languages. On the other hand, a dictionary is a predominantly used data structure in Python. We often convert JSON data to a Python dictionary to seamlessly integrate with Python ecosystem libraries and store data in the database.
The data in JSON format is stored inside the curly brackets. It consists of a key-value pair, each separated by a comma. The components are enclosed in double quotes and separated by a colon. The keys can be repeated; however, it is not recommended to use duplicate keys.
The data in a Python dictionary is stored in the curly brackets and assigned to a defined dictionary variable. It consists of a key-value pair, each separated by a comma. The components are enclosed in single quotes and separated by a colon. The keys must be unique and immutable so that the data can be accessed and manipulated through them.
The json
module in Python offers functionalities related to encoding and decoding data in JSON. Hence, to convert a JSON string to a dictionary, we use the loads
function from this module.
import json
json.loads(jsonString)
This method requires only one necessary parameter:
jsonString
: It is the JSON format string to be converted to a Python dictionary.
Optional parameters for the method:
parse_float
: To specify how the floating point value should be parsed from JSON to dictionary.
parse_int
: To specify how the integer value should be parsed from JSON to dictionary.
encoding
: To specify the type of encoding of the JSON string e.g. 'utf-8'.
cls
: To specify the JSON decoder class to use for parsing.
In this example, we convert a JSON string into a Python dictionary and print their datatypes to see the difference.
import jsonuserJSON = '{"fname" : "Taylor" , "lname" : "Swift"}'print(type(userJSON))print('\nConverting JSON to dictionary:\n')#json to dictionaryuser = json.loads(userJSON)print(user)print(type(user))print('\nFirst Name : ' + user['fname'] + '\n')
Line 1: Import the json
module in Python.
Line 3: Assign a JSON string to userJSON
. The string contains fname
and lname
along with the values.
Line 4: Print the type of the userJSON
string. It will show <class 'str'>
.
Line 8: Assign a dictionary object to user
variable by sending userJSON
as a parameter to the json.loads()
conversion method.
Line 10: Our print user
dictionary and notice that all the values are printed corresponding to their keys.
Line 11: Print the type of the user
object. It will show <class 'dict'>
which shows that the conversion of successful.
Line 12: We can apply simple dictionary operations to the user
object. In this case, we print the value against the fname
key.
Note: We can also convert Python dictionaries to JSON strings.
str = '{"price": 5.54, "qty": 5}'
data = json.loads(str, parse_float=float)
print(data["price"] * data["quantity"])
What will be the output for this?
Free Resources