How to Convert Dictionary to JSON in Python

To convert a dict to json in Python, you can use the json.dumps() method from the json module. To work with any json related operations in Python, import the json module.

Example 1

import json

appDict = {
  'name': 'messenger',
  'playstore': True,
  'company': 'Facebook',
  'price': 100
}

app_json = json.dumps(appDict)
print(app_json)

So, we have defined one dictionary and then converted that dictionary to JSON using json.dumps() method. 

Output

How To Convert Python Dictionary To JSON Tutorial With Example

 

Example 2

To sort the keys, use the sort_keys as the second argument to json_dumps().

import json

personDict = {
  'bill': 'tech',
  'federer': 'tennis',
  'ronaldo': 'football',
  'woods': 'golf',
  'ali': 'boxing'
}

app_json = json.dumps(personDict, sort_keys=True)
print(app_json)

Output

Python Dictionary To JSON Tutorial With Example

The json.dumps() returns the JSON string representation of the python dict.

Example 3

To write JSON data into a file in Python, use the json.dump() method. The json.dump() is a built-in method that converts the objects into suitable json objects.

import json

personDict = {
  'bill': 'tech',
  'federer': 'tennis',
  'ronaldo': 'football',
  'woods': 'golf',
  'ali': 'boxing'
}

with open('person.txt', 'w') as json_file:
  json.dump(personDict, json_file)

In the above program, we have opened the file named person.txt in writing mode using ‘w.’

If a file doesn’t already exist, it will be created. Then, json_dump() transforms the personDict to the JSON string saved in the person.txt file.

The person.txt file is created when you run the above code, the person.txt file is created, and the json string inside that file is written.

That’s it.

1 thought on “How to Convert Dictionary to JSON in Python”

  1. AttributeError Traceback (most recent call last)
    In [34]:
    Line 116: jsonData = json.loads(ms_json)

    AttributeError: ‘bytes’ object has no attribute ‘loads’

    is this a common issue

    Reply

Leave a Comment

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