Summary: In this tutorial, we will learn to convert a python dictionary into JSON and vice versa.
JSON
JSON (JavaScript Object Notation) is a lightweight format to interchange data. It is the text form of a JavaScript object.
The key in JSON is of type “string” with double quotation marks and values could be a string, number, nested JSON, or array of the same.
Example:
{ "lang": "python", "version": 3, "website": "pencilprogrammer.com" }
Note: JSON exist as a string but from the context of data, it is not a string.
Dictionary
A dictionary in python is a mapping between key and value. Key could be a single-quoted string or hash object and the value could be almost of any data type supported in Python.
Example:
{ 'category': ('programming', 'coding') }
Convert Dictionary to JSON
Python has an inbuilt module named ‘json‘ that has comes with methods such as json.dumps()
to convert a dictionary into a JSON string.
The json.dumps()
method accepts a dictionary object as a parameter and returns its corresponding JSON string object.
import json
dict = {'lang': 'python', 'version': 3, 'website': 'pencilprogrammer.com'}
json = json.dumps(dict)
print(json)
Output:
{“website”: “pencilprogrammer.com”, “version”: 3, “lang”: “python”}
Convert JSON to Dictionary
Sometimes we also need to convert a JSON string to a python dictionary in order to parse or extract data.
The json.loads()
method of the ‘json‘ module does exactly the same.
import json
JSON = '{"website": "pencilprogrammer.com", "version": 3, "lang": "python"}'
DICT = json.loads(JSON) #str into a dict
print(DICT['website'])
Output:
pencilprogrammer.com
This type of conversion is often needed when we make an http request in python using the requests.get()
method and receive the response as JSON string from the server.
Example:
import requests, json
#http request to get price of bitcoin
response = requests.get('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd')
#converting json to dictionary
res_dict = json.loads(response.text)
#parse the price from dictionary
price = res_dict["bitcoin"]["usd"]
#output the price
print(f'Bitcoin: ${price}')
Output:
Bitcoin: $58524