1 - About JSON files

JSON (JavaScript Object Notation) is a popular and standard data format used to represent and store structured data made up of attribute-value pairs similar to a Python dictionary. It is common to transmit and receive data between a server and a web application in JSON format. Don't worry though: JSON has long since become language independent and exists as its own standard, so luckily we can skip JavaScript to process json files.

Example: json file describing a person

{"name": "Albert",
"email": "albert99@gmail.com",
"leisure": ["Sport", "Cinema", "Reading", "Travel"]
}

To work with JSON, we must use the json module of Python. To do this, you must import the module before you can use it:

import json

2 - Reading a JSON file or content in Python

2.1 - Reading JSON content

The json module makes it easy to parse JSON strings and files containing a JSON object. You can parse a JSON string using the json.loads () method. The method returns a dictionary.

Example 1: Transform JSON content to a dictionary

import json
person = '{"name": "Albert",
"email": "albert99@gmail.com",
"Leisure": ["Sport", "Cinema",
"Reading", "Travel"]} '
# retrieving content in the form of a dictionary
personDict = json.loads (person)
print (personDict)
# displays: {'name': 'Albert', 'email': 'albert99@gmail.com', 'Leisure': ['Sport', 'Cinema', 'Lecture', 'Voyage']}

# Access the value of a key
print ("hobbies of the person:", personDict ['hobbies'])
# Poster: Leisure of the person: ['Sport', 'Cinema', 'Reading', 'Travel']

2.2 - Reading a JSON file

To read a JSON file, we use the same json.load () method. Suppose you have a file named person.json that contains a JSON object. person.json

{"name": "Albert",
"email": "albert99@gmail.com",
"leisure": ["Sport", "Cinema", "Reading", "Travel"]
}

And now to read this JSON file, we use the following code:

import json

with open ('path_to_file / person.json') as file:
jsonData = json.load (file)

print (jsonData)
# Output: {'name': 'Albert', 'email': 'albert99@gmail.com', 'loisirs': ['Sport', 'Cinema', 'Lecture', 'Voyage']}

3 - Convert a dictionary to a string or to a JSON file

3.1 - Convert a dictionary to a JSON string

In Python, it's easy to convert a dictionary to a JSON string via the json.dumps() method:

Example:

import json

personDict = {'name':
'Albert',
'email': 'albert99@gmail.com',
'leisure': ['Sport', 'Cinema', 'Reading', 'Travel']}
print (type (personDict)) # print

jsonData = json.dumps (personDict)
print (type (jsonData)) # the output is:

Here is a table summarizing Python objects and their equivalents in JSON.

Python Equivalent en JSON
dict object
list, tuple array
str string
int, float number
True true
False false
None null

3.2 - Convert a dictionary to a JSON file

To convert a Python dictionary to a JSON file, we use the json.dump () method (dump without ‘s’)

Example

import json

personDict = {'name': 'Albert',
'email': 'albert99@gmail.com',
'leisure': ['Sport', 'Cinema', 'Reading', 'Travel']
}

with open ('person.json', 'w') as jsonFile:
json.dump (personDict, jsonFile)

After execution, a person.json file is generated:

person.jsom

{"name": "Albert",
"email": "albert99@gmail.com",
"leisure": ["Sport", "Cinema", "Reading", "Travel"]
}

Younes Derfoufi
my-courses.net

Leave a Reply