Flask - Convert a Python Dict to JSON

May 23, 2018 Oclemy Python Flask 8 minutes, 29 seconds

JSON is the most popular data inter-change format these days. The reason for that is because of it's lightweighness and ease of readability. We use it to exchange information across applications especially via HTTP.

Flask being a Web Framework and built on Python, definitely supports JSON. The dict data structure is on the other hand one of the most commonly used python data structures. It's key-value pair mechanism makes it especially suitable for tons of scenarios.

So it's important we know how to turn or convert the dict to JSON format. It's especially suitable to produce an JSON Array of Objects, which is so commonly used. Think something like a JSON Array of user objects.

So we will see how to convert our python dict to JSON Array of Objects.

We are Building a Vibrant YouTube Community

We have a fast rising YouTube Channel of friends. So far we've accumulated more than 2.6 million agreggate views and more than 10,000 subscribeers. Here's the Channel: ProgrammingWizards TV.

Please go ahead subscribe(free obviously) as well. If you have a question or a comment you can post there instead of in this site.People are suggesting us tutorials to do there so you can too.

Here's this tutorial in Video Format.

Let's start.


Introduction to Python Dictionary

A Dictionary generally speaking is a collection of KeyValuePairs. Dictionaries exist in almost all modern popular programming languages in someway or another.

This is because the ability to work with data indexed by keys is very powerful and useful in tons of situations.

In C# Dictionaries are created with the Dictionary class. In Java Dictionary class is available but abstract, so we rely on its children like Hashtable.

In PHP dictionaries are called Associative Arrays.

The most commonly used data structure in Python is list, that is if you ignore str which is also a sequence.

However, list, like other sequences are indexed by a range of integers or numbers. This is good in simple situations but in the real world it may be preferable to index by keys, which may not even be numbers. For example indexing people by their names.

The key in dictionary can be any immutable type, like strings and numbers. You can also use tuples as keys as long as they contain only strings, numbers or tuples. The tupple has to contain immutable objects.

However, because lists are mutable, you cannot use them as keys.

Dictionaries are generally unordered and keys always have to be unique.

Creating a Dictionary

It's as easy as it can get. Just use a pair of curly braces: {}. This creates an empty dictionary.

To add items to the dictionary you place a comma-separated list of key-value pairs.

Here's a dictionary containing with galaxy names as key and galaxy description as values:

galaxies = {'Messier81': 'Messier 81 is a spiral galaxy about 12 million light-years away in the constellation Ursa Major. Due to its proximity to Earth',
            'StarBurst': 'A starburst galaxy is a galaxy undergoing an exceptionally high rate of star formation, as compared to the long-term average..',
            'Cosmos Redshift':'Cosmos Redshift 7 is a high-redshift Lyman-alpha emitter galaxy, in the constellation Sextans, about 12.9 billion light...'
            }

Inserting an Item to Dictionary

Then you can insert a single item into the dictionary in the following manner:

galaxies['Pinwheel'] = 'The Pinwheel Galaxy is a face-on spiral galaxy distanced 21 million light-years away from earth in the constellation Ursa ..'

Getting a Single Item From Dictionary based on the Key

To get a single item from the dictionary if you know the key you do this:

galaxies['StarBurst']

Delete a Dictionary Item

You can delete a single item(KeyValuePair) from a dictionary using del:

del galaxies['StarBurst']

Listing Dictionary Items

To list dictionary items use the dictionary name:

galaxies

Listing Dictionary Keys

To list dictionary keys you use the list() function:

list(galaxies.keys())

Sorting Python Dictionary Items

You can sort dictionary keys using the sorted() function.

sorted(galaxies.keys())

Check if an Item Exists in Python Dictionary.

You can use the in operator to check for existence of item in a dictionary:

'StarBurst' in galaxies # True

or

'StarBurst' not in galaxies # False

Creating Dictionary From Sequence

You can use the dict() constructor to create a dictionary directly from sequences of key-value pairs:

dict([('Messier81', 'Messier description..'), ('StartButs', 'StarBust Description..'), ('Pinwheel', 'Pinwheel Description..')])

Looping Through Dictionary

Most probably you will want to get both keys and values at the same time when iterating or looping through a dictionary in Python. In that case, you use theitems() method to retrieve both keys and values.

for k, v in galaxies.items():
     print(k, v)

Where k is the Key while v is the value.


Python JSON

JSON is a lightweight data interchange format inspired by JavaScript object literal syntax.

Python provides us with the json API to work with JSON data.

Serializing JSON to string

We can serialize a JSON object to a JSON -formated string using the dump() method.

Here's its API definition:

def dumps(obj, **kwargs)

But first you have to import the json module:

>>> import json
>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]

Deserialize JSON to Python Object

You can also decode JSON to Python Object:

>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]

jsonify

This is a function that wraps and adds a few enhancements to the dump() method.

It turns the JSON output into a Response object with the application/json mimetype.

For convenience, it also converts multiple arguments into an array or multiple keyword arguments into a dict. This means that both jsonify(1,2,3) and jsonify([1,2,3]) serialize to [1,2,3].

Here's its API definition:

def jsonify(*args, **kwargs)

Example usage:

    from flask import jsonify  

    @app.route('/_get_current_user')  
    def get_current_user():  
        return jsonify(username=g.user.username,  
                       email=g.user.email,  
                       id=g.user.id)  

This will send a JSON response like this to the browser:

    {  
        "username": "admin",  
        "email": "[email protected]",  
        "id": 42  
    }  

Let's write a full example.

index.py

We only need a single python file, in this case index.py

1. Import Required APIs

Those APIs are all imported from flask module. They include the Flask, json and jsonify.

from flask import Flask,json,jsonify

2. Instantiate Flask

We instantiate it, passing in the current module name:

app = Flask(__name__)

As you can see we've held it in the app variable.

3. Route Our Function

We'll listen to root url or index page requests and invoke the index() function.

@app.route('/')
def index():
    ....

4. Create a Dictionary and Populate it with Data

Dictionaries normally hold keyValuePairs, so we add them to our dictionary:

    galaxies = {'Messier81': 'Messier 81 is a spiral galaxy about 12 million light-years away in the constellation Ursa Major. Due to its proximity to Earth',
            'StarBurst': 'A starburst galaxy is a galaxy undergoing an exceptionally high rate of star formation, as compared to the long-term average..',
            'Cosmos Redshift':'Cosmos Redshift 7 is a high-redshift Lyman-alpha emitter galaxy, in the constellation Sextans, about 12.9 billion light...',
            'Pinwheel': 'The Pinwheel Galaxy is a face-on spiral galaxy distanced 21 million light-years away from earth in the constellation Ursa ..',
            'Sombrero': 'Sombrero Galaxy is an unbarred spiral galaxy in the constellation Virgo located 31 million light-years from Earth',
            'Whirlpool':'The Whirlpool Galaxy, also known as Messier 51a, M51a, and NGC 5194, is an interacting grand-design spiral galaxy ',
            'Andromeda':'The Andromeda Galaxy, also known as Messier 31, M31, or NGC 224, is a spiral galaxy approximately 780 kiloparsecs from',
            'Triangulum':'The Triangulum Galaxy is a spiral galaxy approximately 3 million light-years from Earth in the constellation Triangulum',
            'Canis Majos':'The Canis Major Dwarf Galaxy or Canis Major Overdensity is a disputed dwarf irregular galaxy in the Local Group',
            'Milky Way':'The Milky Way is the galaxy that contains our Solar System. The descriptive milky is derived from the appearance '
            }

5. Create a Python Try-Catch Block

We want to catch any exceptions.

    try:

    except Exception as e:

6. Loop Through Dictionary Adding Items to a Python List

First we create the python list:

galaxyList = []

Then loop through the items in the dictionary, appending the keys and values to the list:

        for name,description in galaxies.items():
            galaxyList.append({ name : description})

Then dump the list, then jsonify and return it.

        return jsonify(json.dumps(galaxyList))

7. Run the App

I run mine in the debug mode. Basically we invoke the run() method of the Flask class, with debug property set to true.

if __name__ == '__main__':
    app.run(debug=True)

Here's the full source code.

Full Code

from flask import Flask,json,jsonify

app = Flask(__name__)

@app.route('/')
def index():
    galaxies = {'Messier81': 'Messier 81 is a spiral galaxy about 12 million light-years away in the constellation Ursa Major. Due to its proximity to Earth',
            'StarBurst': 'A starburst galaxy is a galaxy undergoing an exceptionally high rate of star formation, as compared to the long-term average..',
            'Cosmos Redshift':'Cosmos Redshift 7 is a high-redshift Lyman-alpha emitter galaxy, in the constellation Sextans, about 12.9 billion light...',
            'Pinwheel': 'The Pinwheel Galaxy is a face-on spiral galaxy distanced 21 million light-years away from earth in the constellation Ursa ..',
            'Sombrero': 'Sombrero Galaxy is an unbarred spiral galaxy in the constellation Virgo located 31 million light-years from Earth',
            'Whirlpool':'The Whirlpool Galaxy, also known as Messier 51a, M51a, and NGC 5194, is an interacting grand-design spiral galaxy ',
            'Andromeda':'The Andromeda Galaxy, also known as Messier 31, M31, or NGC 224, is a spiral galaxy approximately 780 kiloparsecs from',
            'Triangulum':'The Triangulum Galaxy is a spiral galaxy approximately 3 million light-years from Earth in the constellation Triangulum',
            'Canis Majos':'The Canis Major Dwarf Galaxy or Canis Major Overdensity is a disputed dwarf irregular galaxy in the Local Group',
            'Milky Way':'The Milky Way is the galaxy that contains our Solar System. The descriptive milky is derived from the appearance '
            }

    try:
        # Initialize an empty galaxies list
        galaxyList = []

        # create a instances for filling up galaxies list
        for name,description in galaxies.items():
            galaxyList.append({ name : description})

        return jsonify(json.dumps(galaxyList))
    except Exception as e:
        print(str(e))
        return jsonify(str(e))

if __name__ == '__main__':
    app.run(debug=True)

Result

Python Flask - Dict to JSON

Best regards.

Comments