• 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 / Convert Dictionary to JSON in Python

Convert Dictionary to JSON in Python

Author: Aditya Raj
Last Updated: February 1, 2023

JSON file formats are used extensively for data transmission. This article will discuss how we can convert a python dictionary to JSON format.

Table of Contents
  1. What is JSON Format?
  2. Convert Python Dictionary to JSON String
  3. Dictionary to JSON File in Python
  4. Error While Converting Dictionary to JSON Format
  5. Conclusion

What is JSON Format?

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data format. It is easy for humans to read and write and for machines to parse and generate. JSON is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999. It is commonly used for exchanging data between a client and a server or between applications.

The data in JSON format is represented as key-value pairs, where the keys are strings and the values can be either strings, numbers, arrays, or other JSON objects. JSON uses a comma-separated list of key-value pairs to represent objects, and square brackets to represent arrays. The data is enclosed in curly braces just like a python dictionary.

Convert Python Dictionary to JSON String

We will use the dumps() method defined in the json module to convert a dictionary to a JSON string. I have discussed the syntax of the dumps() method in this article on working with json files in python. The dumps() method takes the dictionary as its input argument and returns the json string as shown below.

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

Output:

The dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': {'street': '123 Main St', 'city': 'Anytown', 'state': 'CA', 'zipcode': '12345'}, 'email': '[email protected]', 'age': 32}
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}

In the above example, we have passed a python dictionary to the dumps() method. After execution, it returns a JSON string. Observe that the structure of the dictionary and the JSON object are almost the same.

Dictionary to JSON File in Python

To convert a dictionary to a JSON file, we can use the dump() method. The dump() method takes the python dictionary as its first input argument and a file pointer to the destination JSON file as its second input argument. After execution, it saves the dictionary into a JSON file as shown in the following example.

import json
myDict = {
    "name": {
        "first": "John",
        "last": "Doe"
    },
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA",
        "zipcode": "12345"
    },
    "email": "[email protected]",
    "age": 32
}
file=open("person_data.json","w")
json.dump(myDict,file)
file.close()

Output:

The file looks as follows.

JSON File created from a python dictionary
JSON File created from a python dictionary

In this example, we first opened a json file using the open() method in write mode. Then, we used the dump() method to write the dictionary to the json file. Finally, we closed the file using the close() method.

Error While Converting Dictionary to JSON Format

If the python dictionary contains elements other than the primitive data types and container objects such as lists, the above approaches won’t work. For instance, consider the following example.

import json
class Address:
    def __init__(self,street,city,state,zipcode):
        self.street=street
        self.city=city
        self.state=state
        self.zipcode=zipcode
myAddress=Address("123 Main St","Anytown","CA","12345")
myDict = {
    "name": {
        "first": "John",
        "last": "Doe"
    },
    "address": myAddress,
    "email": "[email protected]",
    "age": 32
}
print("The dictionary is:")
print(myDict)
json_string=json.dumps(myDict)
print("The JSON string is:")
print(json_string)

Output:

The dictionary is:
{'name': {'first': 'John', 'last': 'Doe'}, 'address': <__main__.Address object at 0x7fc6544fd9c0>, 'email': '[email protected]', 'age': 32}
TypeError: Object of type Address is not JSON serializable

In this example, we have created a user-defined object of class Address. When we try to convert the dictionary containing the object of type Address to JSON, the dumps() method doesn’t know how to convert the Address object to JSON. Hence, it raises a python TypeError exception.

To avoid this error, you can direct the dump() or dumps() method to convert custom python objects into json files. For this, you can read this article on custom json encoder in python.

Conclusion

In this article, we have discussed ways to convert a dictionary to a JSON string or file in python. 

To learn more about python programming, you can read this article on how to create a chat app in Python. You might also like this article on linear regression using the sklearn module in Python.

Stay tuned for more informed 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