Skip to content

Python JSON string to dict

  • by

Use Python’s built-in JSON load() function to convert JSON string to dict. This function takes a json object as input and converts it to the dictionary.

Python JSON string to dict example

A simple example code passes the json object to the load function.

import json

jsonData = '{"firstName": "Edward", "lastName": "John"}'

res = json.loads(jsonData)

print(res)
print(res['firstName'])
print(res['lastName'])
print(type(res))

Output:

Python JSON string to dict

Here is a simple snippet that read’s in a json text file from a dictionary. Note that your json file must follow the json standard, so it has to have " double quotes rather then ' single quotes.

Your JSON dump.txt File:

{"test":"1", "test2":123}

Python Script:

import json
with open('/your/path/to/a/dict/dump.txt') as handle:
    dictdump = json.loads(handle.read())

Convert a JSON file into a dictionary

import json
  

with open('data.json') as json_file:
    data = json.load(json_file)
    
    print("Type:", type(data))
  
    print("\nData:", data['Info'])

Do comment if you have any doubts or suggestions on this Python JSON dictionary 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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading