Python has a built-in json module, which can be used to work with JSON data. See below the syntax of Import the json module:
JSON can store Lists, bools, numbers, tuples, and dictionaries.
import json
The JSON module is mainly used to convert the python dictionary above into a JSON string that can be written into a file.
json_string = json.dumps(datastore)
How to import JSON in Python
Simple example code in PycCharm IDE. Python JSON dumps method with an indent.
import json
data = '[{"ID":101,"Name":"John","Role":"Member"},' \
'{"ID":102,"Name":"Kenny","Role":"Editor"}]'
res = json.loads(data)
json_str = json.dumps(res, indent=2)
print(json_str)
Screen GIF:
Convert from Python to JSON
You can convert an Object into a JSON string by using the json.dumps() method in Python.
import json
# a dict object
d = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
res = json.dumps(d)
print(res)
Output: {“name”: “John”, “age”: 30, “city”: “New York”}
Do comment if you have any doubts or suggestions on this Python JSON topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.