Lesson 1: JSON

JSON is a very convenient format that’s used by many data structures, web services and particularly REST API solutions.

You can quickly learn it to use it in practical operations with Python.

Function 1: json.loads()

Loads json data into a Python data structure such as list or dictionary from a string.

Used Where?

  • Data storage and transfer. APIs are one of the most common sources of JSON format data.

Syntax do(s)

1) Before using json module in Python make sure you import it.

json.loads() will load your json data into a list

json.dumps() will dump your json data into a string.

Syntax don't(s)

1) indent=# parameter (explained under Advanced topic) is only used for .dumps() method and not the .loads() method.

Example 1

>>> data = “[{\”word\”:\”etiquette\”,\”score\”:1648,\”numSyllables\”:3},{\”word\”:\”aesthetic it\”,\”numSyllables\”:4},{\”word\”:\”arithmetic it\”,\”numSyllables\”:5},{\”word\”:\”geomagnetic cut\”,\”numSyllables\”:6},{\”word\”:\”pathetic it\”,\”numSyllables\”:4}]”

>>> import json
>>> data = json.loads(data):
>>> print(data)

[{'word': 'etiquette', 'score': 1648, 'numSyllables': 3}, 
{'word': 'aesthetic it', 'numSyllables': 4}, 
{'word': 'arithmetic it', 'numSyllables': 5}, 
{'word': 'geomagnetic cut', 'numSyllables': 6}, 
{'word': 'pathetic it', 'numSyllables': 4}]

Function 2: json.dumps()

Dumps json data into a string.

You can make your if statement more sophisticated by adding an else statement when needed.

Next 2 examples will clarify the implementation of this idea for you:

Tips

1- Requests library also has a json() method which can be confused with json library and it json.loads() and json.dumps() methods. Requests library’s json() method is a nice touch that can be used to convert data to json format inside the requests library.

Advanced Concepts (Optional)

1- You can use indentation with json.dumps() method so that the output will appear more beautiful and structured. Just add the parameter: indent=3 to inside the json.dumps() paranthesis.

Example 2

>>> data = [{“word”:”etiquette”,”score”:1647,”numSyllables”:3},{“word”:”aesthetic it”,”numSyllables”:4},{“word”:”arithmetic it”,”numSyllables”:5},{“word”:”geomagnetic cut”,”numSyllables”:6},{“word”:”pathetic it”,”numSyllables”:4}]

>>> import json
>>> data = json.dumps(data, indent=4):
>>> print(data)

"[
    {
        "word": "etiquette",
        "score": 1647,
        "numSyllables": 3
    },
    {
        "word": "aesthetic it",
        "numSyllables": 4
    },
    {
        "word": "arithmetic it",
        "numSyllables": 5
    },
    {
        "word": "geomagnetic cut",
        "numSyllables": 6
    },
    {
        "word": "pathetic it",
        "numSyllables": 4
    }
]"

Exercises: na