AppDividend
Latest Code Tutorials

How to Convert Python JSON to Dict

0

JSON stands for JavaScript Object Notation. JSON is a lightweight format that is used to save and exchange data. The data in JSON is represented as quoted-strings consisting of key-value mapping enclosed between curly braces { }.

Python JSON to Dict

To convert Python JSON to dict, use the json.loads() function. The json.loads() function can parse the valid JSON string and convert it into a Python Dictionary. The loads() function takes a string as a parameter and returns the dictionary.

Syntax

json.loads(str)

Parameters

The loads() function takes str, bytes, or byte array instance, containing the JSON document as parameter str.

Example

To work with json module, import the json module, and then you will be able to use the loads() method.

import json

data = '{ "name":"WandaVision", "service":"Disneyplus", "city":"New York"}'

# parse the data
dict = json.loads(data)
print(dict)

Output

{'name': 'WandaVision', 'service': 'Disneyplus', 'city': 'New York'}

And in the output, we get the dictionary with key-value pairs as elements.

Let’s say that if the json JSON string looks like this, then what will be the output.

data = """{ 
        "name":"WandaVision", 
        "service":"Disneyplus", 
        "city":"New York"
        }"""

This is a multiline strings with triple quotes. Let’s convert this into a dictionary using the loads() function.

import json

data = """{ 
        "name":"WandaVision", 
        "service":"Disneyplus", 
        "city":"New York"
        }"""

# parse x:
dict = json.loads(data)
print(dict)

Output

{'name': 'WandaVision', 'service': 'Disneyplus', 'city': 'New York'}

How to Read JSON File in Python

To read a json file in Python, use the json.load() method. Let’s say I have a data.json file in my project directory than to read and print the content on the console, write the following code.

import json

with open("data.json") as f:
    data = json.load(f)

print(data)

Output

'data': [{'color': 'red', 'value': '#f00'}, 
         {'color': 'green', 'value': '#0f0'}, 
         {'color': 'blue', 'value': '#00f'},
         {'color': 'black', 'value': '#000'}]}

Here, we have used the with statement with open() function to read the json file. Then, the file is parsed using json.load() method which gives us a dictionary named data.

That is it for converting Python json to dictionary data type.

See also

Python json dumps()

Python json parse

Pandas JSON To CSV

Python Set to JSON

Python Tuple to JSON

Leave A Reply

Your email address will not be published.

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