• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Load JSON into a Python Dictionary

Load JSON into a Python Dictionary

Author: Aditya Raj
Last Updated: February 8, 2023

Softwares often use JSON file format to store and transmit data. While writing software in python, we might need to convert a JSON string or file into a python object. This article discusses how to load JSON into a python dictionary.

Table of Contents
  1. What is JSON Format?
  2. Convert JSON String to Python Dictionary
  3. Convert JSON File to Python Dictionary
  4. Convert JSON to User-defined Python Objects
  5. Conclusion

What is JSON Format?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and for machines to parse and generate.

The syntax of JSON consists of keys and values, separated by a colon (:), and surrounded by curly braces ({}). The keys must be strings, and the values can be any data type including strings, numbers, arrays, and objects.

For example, the following JSON string contains data of an employee.

{
  "employee": {
    "name": "John Doe",
    "age": 35,
    "job": {
      "title": "Software Engineer",
      "department": "IT",
      "years_of_experience": 10
    },
    "address": {
      "street": "123 Main St.",
      "city": "San Francisco",
      "state": "CA",
      "zip": 94102
    }
  }
}

Here,

  • The name of the employee is “John Doe”.
  • The age of the employee is 35.
  • The job title of the employee is “Software Engineer”.
  • The department the employee works in is “IT”.
  • The employee has 10 years of experience in the field.
  • The employee’s address includes street name “123 Main St.”, city “San Francisco”, state “CA”, and zip code 94102.

You can observe that the JSON format is almost similar to the format of a python dictionary. 

Convert JSON String to Python Dictionary

To load a json string into a python dictionary, you can use the loads() method defined in the json module. The loads() method takes the JSON string as its input argument and returns the dictionary as shown below.

import json
json_string='{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}'
print("The JSON string is:")
print(json_string)
python_dict=json.loads(json_string)
print("The python dictionary is:")
print(python_dict)

Output:

The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
The python dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}

While using the loads() method, you should pass a valid JSON string as an input argument. Otherwise, the program will run into an error.

Instead of using the loads() function, you can also use the JSONDecoder class to convert a JSON string to python dictionary. The JSONDecoder class is defined in the json module and has a decode() method.

When the decode() method is invoked on the JSONDecoder object, it takes a json string as its input argument. After execution, it returns a dictionary as shown below.

import json
json_string='{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}'
print("The JSON string is:")
print(json_string)
python_dict=json.JSONDecoder().decode(json_string)
print("The python dictionary is:")
print(python_dict)

Output:

The JSON string is:
{"name": {"first": "John", "last": "Doe"}, "address": {"street": "123 Main St", "city": "Anytown", "state": "CA", "zipcode": "12345"}, "email": "[email protected]", "age": 32}
The python dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}

Suggested Reading: Working with JSON files in Python

Convert JSON File to Python Dictionary

If we have a JSON file instead of a json string, we can also convert it to a dictionary. For this, we will use the following steps.

  • First, we will open the JSON file in read mode using the open() function. The open() function takes the file name as its first input argument and the python literal “r” as its second input argument. After execution, it returns a file pointer. 
  • Next, we will pass the file pointer to the load() method defined in the json module. The load() method will return the python dictionary after execution. 

You can observe this in the following example.

import json
file=open("person_data.json","r")
python_dict=json.load(file)
print("The python dictionary is:")
print(python_dict)

Output:

The python dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}

Convert JSON to User-defined Python Objects

Instead of obtaining a dictionary, we can also convert a JSON file or string to a custom python object. For this, you can read this article on custom JSON decoder in python.

Conclusion

In this article, we have discussed how to load a json string or file to a dictionary. To learn more about python programming, you can read this article on how to convert JSON to YAML in Python. You might also like this article on custom json encoders in python.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us