All You Need To Know About Python JSON Module
Tags: python, beginners, programming, codenewbie
Published: 2021-07-31 00:57:48

Hello everybody,
I'm [Aya Bouchiha](https://t.me/AyaBouchiha),
on this amazing day, we'll discuss using the **JSON** module in python

## What's JSON

> **JSON**: (_JavaScript Object Notation_) is a syntax for serializing objects, arrays, numbers, strings, booleans, and null. It is based upon JavaScript syntax but is distinct from it: some JavaScript is not JSON.
>
> -   [www.developer.mozilla.org](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON)

## JSON Syntax rules

-   Data have to be written as key-value pairs.
-   Data is separated by commas.
-   Curly braces hold objects.
-   Square brackets hold arrays.
-   string has to be written inside double quotes "", instead of single quotes ''.

```JSON
[
	{
		"id": 1,
		"name": "Aya Bouchiha",
		"job": "full-stack developer",
		"contact_info": {
			"email": "developer.aya.b@gmail.com",
			"telegram": "https://t.me/AyaBouchiha"
		},
		"isMoroccan": true,
		"facebook_account": null,
		"favorite_subjects": [
			"programming",
			"math",
			"physics",
			"english",
			"french"
		]
	}
]
```

## Example of a JSON file

**tasks.json**

```JSON
[
	{
		"id": 1,
		"username": "Aya Bouchiha",
		"title": "eat fruits",
		"completed": true
	},
	{
		"id": 2,
		"username": null,
		"title": "go to gym",
		"completed": true
	},
	{
		"id": 3,
		"username": null,
		"title": "drink an orange jus",
		"completed": true
	},
	{
		"id": 4,
		"username": "John Doe",
		"title": "practice english",
		"completed": false
	}
]
```

## Using JSON in python

### Python objects and their equivalent conversion to JSON

| python             | json   |
| ------------------ | ------ |
| str                | string |
| int, long or float | number |
| list               | array  |
| dict               | object |
| True               | true   |
| False              | false  |
| None               | null   |

### Importing JSON module in python

json is a built-in package in python for encoding and decoding JSON data.

```python
import json
```

## Serializing JSON

### json.dumps

**_json.dumps()_**: lets you convert a python dictionary to JSON as a _string_.

```python
import json

task = {
		'id': 1,
		'username': None,
		'title': 'eat fruits',
		'completed': True
}

print(json.dumps(task))
```

_Output:_

```json
{"id": 1, "name": null, "title": "eat fruits", "completed": true}

<class 'str'>
```

### json.dump()

**_json.dump_()** lets you converts a python dictionnary to JSON in a specified **file**.

```python
import json

user_dict =  {
	'id': 1,
    'name': 'Aya Bouchiha',
    'job': 'full-stack developer',
    'contact_info': {
	   'email': 'developer.aya.b@gmail.com',
	   'telegram': 'https://t.me/AyaBouchiha'
	},
   'isMoroccan': True,
   'facebook_account': None,
   'favorite_subjects': ['programming', 'math', 'physics', 'english', 'french']
}


with open('user.json', "w") as user_file:
	json.dump(user_dict, user_file)
```

**Output:**

**user.json**

```json
{"id": 1, "name": "Aya Bouchiha", "job": "full-stack developer", "contact_info": {"email": "developer.aya.b@gmail.com", "telegram": "https://t.me/AyaBouchiha"}, "isMoroccan": true, "facebook_account": null, "favorite_subjects": ["programming", "math", "physics", "english", "french"]}
```

There is a problem here, we find that our json data is not organized and not easy to read, that's why the **indent**  parameter comes, it lets you specify the indentation size for nested structures. this parameter takes by default None. To understand better let's try the same example with an indentation size of 2.

```python
with open('user.json', "w") as user_file:
	json.dump(user_dict, user_file, indent=2)
```

*Output:*

**user.json**
```json
{
  "id": 1,
  "name": "Aya Bouchiha",
  "job": "full-stack developer",
  "contact_info": {
    "email": "developer.aya.b@gmail.com",
    "telegram": "https://t.me/AyaBouchiha"
  },
  "isMoroccan": true,
  "facebook_account": null,
  "favorite_subjects": [
    "programming",
    "math",
    "physics",
    "english",
    "french"
  ]
}
```

What about indent=4 :) ?

```python
with open('user.json', "w") as user_file:
	json.dump(user_dict, user_file, indent=4)
```

Output:

**user.json**

```json
{
    "id": 1,
    "name": "Aya Bouchiha",
    "job": "full-stack developer",
    "contact_info": {
        "email": "developer.aya.b@gmail.com",
        "telegram": "https://t.me/AyaBouchiha"
    },
    "isMoroccan": true,
    "facebook_account": null,
    "favorite_subjects": [
        "programming",
        "math",
        "physics",
        "english",
        "french"
    ]
}
```

Now, our json file looks better, but how can we sort our keys? 

**sort_keys**: lets you sort keys in ascending order if it is *True*, however, **sort_keys** takes by default *False*. 
Let's take an example

```python
import json

user_dict =  {
	'id': 1,
    'name': 'Aya Bouchiha',
    'job': 'full-stack developer',
    'contact_info': {
	   'email': 'developer.aya.b@gmail.com',
	   'telegram': 'https://t.me/AyaBouchiha'
	},
   'isMoroccan': True,
   'facebook_account': None,
   'favorite_subjects': ['programming', 'math', 'physics', 'english', 'french']
}


with open('user.json', "w") as user_file:
	json.dump(user_dict, user_file, indent=4, sort_keys=True)
```

*Output:*

**user.json**
```json
{
    "contact_info": {
        "email": "developer.aya.b@gmail.com",
        "telegram": "https://t.me/AyaBouchiha"
    },
    "facebook_account": null,
    "favorite_subjects": [
        "programming",
        "math",
        "physics",
        "english",
        "french"
    ],
    "id": 1,
    "isMoroccan": true,
    "job": "full-stack developer",
    "name": "Aya Bouchiha"
}
```

#### **Note:**
You can use **indent** and **sort_key** parameters in **json.dump()** and also **json.dumps()**.

## Deserializing JSON

## json.loads()

**json.loads()**: translate JSON string to a Python object.

```python
import json

user_json ='''[
	{
		"id": 1,
		"name": "Aya Bouchiha",
		"job": "full-stack developer",
		"contact_info": {
			"email": "developer.aya.b@gmail.com",
			"telegram": "https://t.me/AyaBouchiha"
		},
		"isMoroccan": true,
		"facebook_account": null,
		"favorite_subjects": [
			"programming",
			"math",
			"physics",
			"english",
			"french"
		]
	}
]'''

user = json.loads(user_json)

print(user)
print(type(user))
```

*Output:*
```python
[{'id': 1, 'name': 'Aya Bouchiha', 'job': 'full-stack developer', 'contact_info': {'email': 'developer.aya.b@gmail.com', 'telegram': 'https://t.me/AyaBouchiha'}, 'isMoroccan': True, 'facebook_account': None, 'favorite_subjects': ['programming', 'math', 'physics', 'english', 'french']}]
<class 'list'>
```

## json.load()

**json.load()**: lets you read a JSON document from a file and translate it to a python object.

**user.json**
```json
[
	{
		"id": 1,
		"name": "Aya Bouchiha",
		"job": "full-stack developer",
		"contact_info": {
			"email": "developer.aya.b@gmail.com",
			"telegram": "https://t.me/AyaBouchiha"
		},
		"isMoroccan": true,
		"facebook_account": null,
		"favorite_subjects": [
			"programming",
			"math",
			"physics",
			"english",
			"french"
		]
	}
]
```

**file.py**:
```python
import json

with open('user.json', 'r') as user_file:
    user = json.load(user_file)

print(user)
print(type(user))
```

*output*:

```python
[{'id': 1, 'name': 'Aya Bouchiha', 'job': 'full-stack developer', 'contact_info': {'email': 'developer.aya.b@gmail.com', 'telegram': 'https://t.me/AyaBouchiha'}, 'isMoroccan': True, 'facebook_account': None, 'favorite_subjects': ['programming', 'math', 'physics', 'english', 'french']}]
<class 'list'>
```

### Summary

**JSON**: (_JavaScript Object Notation_) is a syntax for serializing objects, arrays, numbers, strings, booleans, and null.

**json.dumps()**: converts a python dictionnary to JSON as a _string_.

**json.dump()**  converts a python dictionnary to JSON in a specified **file**.

**json.loads()**: translate JSON string to a Python object.

**json.load()**: lets you read a JSON document from a file and translate it to a python object.

## References & Useful Ressources

+ [https://realpython.com/python-json/](https://realpython.com/python-json/)

+ [https://www.programiz.com/python-programming/json](https://www.programiz.com/python-programming/json)

+ [https://docs.python.org/3/library/json.html](https://docs.python.org/3/library/json.html)

+ [https://www.youtube.com/watch?v=9N6a-VLBa2I](https://www.youtube.com/watch?v=9N6a-VLBa2I)

+ [https://www.youtube.com/watch?v=T6uCFDRVoRE](https://www.youtube.com/watch?v=T6uCFDRVoRE)

+ [https://www.w3schools.com/python/python_json.asp](https://www.w3schools.com/python/python_json.asp)

To Contact Me:

email: developer.aya.b@gmail.com

telegram: [Aya Bouchiha](https://t.me/AyaBouchiha)

Have a great day!