AppDividend
Latest Code Tutorials

Python dict to json | Convert Python Dictionary To JSON

0

Python json.dumps() is an inbuilt function that converts the dictionary to string object, not the json(dictionary) object! so you have to load your string into a dict to use it by using the json.loads() method. So, if you want to convert Python dict to json then first you have to convert a dictionary to string and then using json.loads() method convert into JSON.

You can check out the How to Parse JSON in Python. JSON (JavaScript Object Notation) is the popular data format used for presenting the structured data. It’s a prevalent practice to transmit and receive data between the server and web application in JSON format.

Convert Python dict to json

If you have a Python object, you can convert it into a JSON string by using the json.dumps() method. If you want to work with JSON (string, or file containing the JSON object), you can use the Python’s json module. You need to import a module before you can use it.

import json

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

Now, you can convert a dictionary to JSON string using the json.dumps() method.

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

You may also hear the term marshaling, but that’s the whole other discussion. 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 convert 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 following.

Python Dictionary To JSON Tutorial With Example

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

Writing JSON to a file

If we want to write JSON to a file in Python, we can use json.dump() method.

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 which will be saved in the person.txt file.

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 is following.

# app.py

import json

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

Now, if you run the above file then you can see that 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

If you need to create the dictionary with all names inside double quotes instead of default single quotes which Python uses then you can 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

Finally, How To Convert Python Dictionary To JSON Example is over.

Recommended Posts

Python list to json

Python Dictionary to DataFrame

Python Dictionary to CSV

Python string to list

Python string to int

Leave A Reply

Your email address will not be published.

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