How to use the json file in python- read and extract data

1. About the JSON file

JSON files are commonly used for data exchange between systems and are easily interpreted by various programming languages. They offer a human-readable and compact structure that is easy to parse and generate. JSON’s widespread adoption and compatibility have made it a popular choice for data representation in web services, APIs, and configuration files.

  1. A JSON (JavaScript Object Notation) file: is a text-based data format commonly used for storing and transmitting structured information. It provides a lightweight and readable way to represent data objects and their properties.
  2. JSON files consist of two main components: objects and arrays. An object is a collection of key-value pairs enclosed within curly braces {}. Each key is a string that uniquely identifies the corresponding value. Values can be of various types, including strings, numbers, booleans, null, arrays, or nested objects. Objects allow for the organization and representation of complex data structures.
  3. Arrays, on the other hand: are ordered lists of values enclosed within square brackets []. They can contain values of any JSON data type, including objects, arrays, strings, numbers, booleans, or null. Arrays are useful when dealing with multiple related values or when maintaining a specific order is important.
  4. Strings in JSON: are sequences of characters enclosed in double quotation marks. They can contain any valid Unicode character and support escape sequences for special characters.
  5. Numbers in JSON: can represent integers or floating-point values and are not enclosed in quotation marks. They follow the same syntax rules as most programming languages.
  6. Boolean values in JSON: are represented as either true or false and are not enclosed in quotation marks. They represent the logical values of true and false, respectively.
  7. The null value in JSON: indicates the absence of a value or an empty value.

Example: json file describing a person

{"name": "Albert",
"email": "",
"leisure": ["Sport", "Cinema", "Reading", "Travel"]

To work with JSON file, 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": "", 
"Leisure": ["Sport", "Cinema", 
"Reading", "Travel"]} '
# retrieving content in the form of a dictionary
personDict = json.loads (person)
print (personDict)
# displays: {'name': 'Albert', 'email': '', '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": "",
"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': '', '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:


import json
personDict = {'name':
                'email': '',
                'leisure': ['Sport', 'Cinema', 'Reading', 'Travel']}
print (type (personDict)) # output: <class 'dict'>
jsonData = json.dumps (personDict)
print (type (jsonData)) # output: <class 'str'>

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

Python Equivalent in 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’)


import json

personDict = {'name': 'Albert',
                'email': '',
                'leisure': ['Sport', 'Cinema', 'Reading', 'Travel']

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

After execution, a person.json file is generated:


{"name": "Albert",
 "email": "",
 "leisure": ["Sport", "Cinema", "Reading", "Travel"]

Leave a Reply