Import JSON in Python

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 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:

Import JSON in Python

Convert from Python to JSON

You can convert Object it 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 and suggestions on this Python JSON topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.