Home Reading and writing JSON with Python
Post
Cancel

Reading and writing JSON with Python

JSON (JavaScript Object Notation) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values). It is a common data format with diverse uses in electronic data interchange, including that of web applications with servers.

source: https://en.wikipedia.org/wiki/JSON

This is a small example of handling Python dictionaries and JSON.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import json

person_dict = [
    {
        "id" : "1234",
        "name" : "John Doe",
        "department" : "Marketing",
        "place" : "Remote"
    },
    {
        "id" : "76543",
        "name" : "Jane Doe",
        "department" : "Software Engineering",
        "place" : "Remote"
    },
    {
        "id" : "34567",
        "name" : "Don Joe",
        "department" : "Software Engineering",
        "place" : "Office"
    }
]


print("Print the entire python dictionary:")
print(person_dict)
print()

# Convert the dictionary to JSON
json_data = json.dumps(person_dict, indent = 4)

print("Printing the JSON data:")
print(json_data)
print()

# Convert back to a dictionary
print("Printing the converted dictionary:")
data = json.loads(json_data)
print(data)

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Print the entire python dictionary:
[{'id': '1234', 'name': 'John Doe', 'department': 'Marketing', 'place': 'Remote'}, {'id': '76543', 'name': 'Jane Doe', 'department': 'Software Engineering', 'place': 'Remote'}, {'id': '34567', 'name': 'Don Joe', 'department': 'Software Engineering', 'place': 'Office'}]

Printing the JSON data:
[
    {
        "id": "1234",
        "name": "John Doe",
        "department": "Marketing",
        "place": "Remote"
    },
    {
        "id": "76543",
        "name": "Jane Doe",
        "department": "Software Engineering",
        "place": "Remote"
    },
    {
        "id": "34567",
        "name": "Don Joe",
        "department": "Software Engineering",
        "place": "Office"
    }
]

Printing the converted dictionary:
[{'id': '1234', 'name': 'John Doe', 'department': 'Marketing', 'place': 'Remote'}, {'id': '76543', 'name': 'Jane Doe', 'department': 'Software Engineering', 'place': 'Remote'}, {'id': '34567', 'name': 'Don Joe', 'department': 'Software Engineering', 'place': 'Office'}]
This post is licensed under CC BY 4.0 by the author.