In this article, we will discuss how to convert a dictionary object into JSON in python.
JSON
JSON (JavaScript Object Notation) is a lightweight format to interchange data. It is the text form of a javascript object. The key is of type “string “with double quotation marks and values can be string, number, nested json or array of the same.
1 | { "lang": "python", "version": 3, "website": "pencilprogrammer.com" } |
Dictionary
Dictionary in python is a mapping between key and value. Key can be a single-quoted string or hash object and the value can be almost any data type supported in python.
1 | { 'category': ('programming', 'coding') } |
Convert Dictionary to JSON
Python comes with an inbuilt module ‘json‘ to work with JSON. All we need is to import it in our program and use json.dumps()
which takes a dictionary object as parameter and returns the corresponding json string object.
1 2 3 4 5 6 | import json dict = {'lang': 'python', 'version': 3, 'website': 'pencilprogrammer.com'} json = json.dumps(dict) print(json) |
output
1 | {"website": "pencilprogrammer.com", "version": 3, "lang": "python"} |
Now you can easily transfer data as JSON string.
Convert JSON to Dictionary
Sometimes you also want to convert a JSON string to python dictionary in order to parse or extract data. json.loads()
method of ‘json’ module can convert a JSON string back to a dictionary object.
Let’s see an example in python.
1 2 3 4 5 6 | import json JSON = '{"website": "pencilprogrammer.com", "version": 3, "lang": "python"}' DICT = json.loads(JSON) #str into a dict print(DICT['website']) |
output
1 | pencilprogrammer.com |
I hope you find this post useful. If you have any doubts or suggestion then please comment below.