AppDividend
Latest Code Tutorials

Python dict to json: How to Convert Dictionary to JSON

JSON (JavaScript Object Notation) is the famous data format used for presenting structured data. It’s a prevalent practice to transmit and receive data between the server and web application in JSON format.

You can check out the How to Parse JSON in Python. To load a string into a dict, use the json.loads() method. If you have a Python object, you can convert it into a JSON string using the json.dumps() method.

Python dict to json

To convert Python dict to json, use the json.dumps() method. The json.dumps() is a built-in Python function that converts the dictionary to a string object. The “json” module makes it easy to parse the JSON strings which contain the JSON object.

To work with any json related operations in Python, use Python’s json module. It will help if you import json a module before using it.

import json

The json module makes it easy to parse the JSON strings and files containing the JSON object.

You can convert a dictionary to a JSON string using the json.dumps() method.

The process of encoding the JSON is usually called serialization. That term refers to transforming data into a series of bytes (hence serial) stored or transmitted across the network.

You may also hear the term marshaling, but that’s the whole other discussion. So naturally, deserialization is a reciprocal process of decoding data that has been stored or delivered in the JSON standard.

See the following example.

# app.py

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. The output is the following.

How To Convert Python Dictionary To JSON Tutorial With Example

If you want to sort the keys, use the sort_keys as the second argument to json_dumps().

See the following example.

# app.py

import json

personDict = {
  'bill': 'tech',
  'federer': 'tennis',
  'ronaldo': 'football',
  'woods': 'golf',
  'ali': 'boxing'
}
app_json = json.dumps(personDict, sort_keys=True)
print(app_json)

The output is the following.

Python Dictionary To JSON Tutorial With Example

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

Write JSON to a file in Python

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

See the following code.

# app.py

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.

Python dump dict to json file

Let’s say you have a dictionary like this.

# app.py

data = {'Eleven': 'Millie',
        'Mike': 'Finn',
        'Will': 'Noah'}

Now, you have to dump this dict to json to a file, then the easier way to do it is by following.

# app.py

import json

data = {'Eleven': 'Millie',
        'Mike': 'Finn',
        'Will': 'Noah'}
with open('app.json', 'w') as fp:
    json.dump(data, fp)

If you run the above file, you can see that the app.json file is created, and then it has the following content.

{ "Eleven": "Millie", "Mike": "Finn", "Will": "Noah" }

The above example is a simple case of File handling in Python. We have used the File open() Function in Python.

Python dict to json double quotes

To create a dictionary with all names inside double quotes instead of default single quotes, use the following code.

# app.py

import json


class App(dict):
    def __str__(self):
        return json.dumps(self)


couples = [['eleven', 'Millie'],
           ['mike', 'Finn'],
           ['max', 'Sadie'],
           ['dustin', 'Gaten']]

pairs = App(couples)
print(pairs)

See the output.

➜  pyt python3 app.py
{"eleven": "Millie", "mike": "Finn", "max": "Sadie", "dustin": "Gaten"}
➜  pyt

That’s it for this tutorial.

Recommended Posts

Python list to json

Python Dictionary to DataFrame

Python Dictionary to CSV

Python string to list

Python string to int

1 Comment
  1. Hannah Dean says

    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

Leave A Reply

Your email address will not be published.

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