Python

Python JSON Example

Hello in this tutorial, we will understand how to parse, read, and write JSON in python programming.

1. Introduction

JSON stands for Javascript Object Notation and is a popular format to represent structured data. It is the most popular exchange of data format between the application running on the server and the client. In python, JSON exists as a string such as –

person_data = '{"id":1,"first_name":"Marci","last_name":"Larmet","email":"mlarmet0@topsy.com","gender":"Genderfluid"}'

In python programming, we import the inbuilt json module to work with. This module makes it easy to parse the JSON strings and files containing the JSON data.

1.2 Setting up Python

If someone needs to go through the Python installation on Windows, please watch this link. You can download the Python from this link.

2. Python JSON Example

I am using JetBrains PyCharm as my preferred IDE. You are free to choose the IDE of your choice. Let us dive in with the programming stuff now.

2.1 Python dict to JSON string

Let us understand this in python programming. We will use:

  • The json.dumps(…) method to convert the JSON data to a string
  • The pretty-print to print the data in a readable format by adding the optional indent parameter to the json.dumps(…) method. By default the value of indent is None

Python dict to JSON string

# python json tutorial

import json

person_dict = {
    "id": 2,
    "first_name": "Ivett",
    "last_name": "Oldall",
    "email": "ioldall1@paypal.com",
    "gender": "Male",
    "phone": "860-554-1988"
}

# converting to json string
# printing json data in pretty print
data_json = json.dumps(person_dict, indent=2)
print(data_json)

If everything goes well the following output will be shown in the IDE console.

Console output

{
  "id": 2,
  "first_name": "Ivett",
  "last_name": "Oldall",
  "email": "ioldall1@paypal.com",
  "gender": "Male",
  "phone": "860-554-1988"
}

2.2 Write JSON data to file

Let us understand this in python programming.

Write JSON data to file

# python json tutorial

import json

# file params
file_path = 'config'
file_name = 'emp.json'

data_dict = {
    "person": [
        {"id": 1, "first_name": "Iorgos", "last_name": "McPaike", "email": "imcpaike0@issuu.com",
         "gender": "Genderqueer", "phone": "584-868-2320"},
        {"id": 2, "first_name": "Vinnie", "last_name": "De Gogay", "email": "vdegogay1@utexas.edu",
         "gender": "Agender", "phone": "897-932-4821"},
        {"id": 3, "first_name": "Marcille", "last_name": "Pitkaithly", "email": "mpitkaithly2@cbslocal.com",
         "gender": "Genderqueer", "phone": "139-842-9277"},
        {"id": 4, "first_name": "Bob", "last_name": "Woltering", "email": "bwoltering3@mediafire.com",
         "gender": "Genderfluid", "phone": "593-291-4767"},
        {"id": 5, "first_name": "Ginni", "last_name": "Circuit", "email": "gcircuit4@quantcast.com",
         "gender": "Genderfluid", "phone": "704-200-9520"}
    ]
}


def write_json(destination):
    # if the file doesn't already exist, it will be created
    with open(destination, 'w') as json_file:
        json.dump(data_dict, json_file)

    print('Successfully written to {}'.format(file_name))


if __name__ == '__main__':
    write_json(file_path + '/' + file_name)

If everything goes well the following output will be shown in the IDE console and the file emp.json containing the JSON format data will be created at the given location.

Console output

Successfully written to emp.json

2.3 Read JSON data from file

Let us understand this in python programming.

Read JSON data from file

# python json tutorial

import json
import pathlib

# file params
file_path = 'config'
file_name = 'data.json'


def read_json(destination):
    # checking is file exists at the given destination or not
    if pathlib.Path(destination).exists():
        with open(destination, 'r') as f:
            data = json.load(f)

        if not data['person']:
            print('No data!')
        else:
            print('Data from json file')
            print('--------------------------')

            # printing json data in pretty print
            # print(json.dumps(data, indent=2))

            for rows in data['person']:
                full_name = rows['first_name'] + ' ' + rows['last_name']
                print('Id = {}, Full name = {}, Email = {}, Gender = {}'.format(
                    rows['id'], full_name, rows['email'], rows['gender']
                ))
    else:
        print('File not exist!')


if __name__ == '__main__':
    read_json(file_path + '/' + file_name)

If everything goes well the following output will be shown in the IDE console.

Console output

Data from json file
--------------------------
Id = 1, Full name = Marci Larmet, Email = mlarmet0@topsy.com, Gender = Genderfluid
Id = 2, Full name = Nowell Malatalant, Email = nmalatalant1@eventbrite.com, Gender = Male
Id = 3, Full name = Napoleon Copo, Email = ncopo2@com.com, Gender = Bigender
Id = 4, Full name = Humfrey Romand, Email = hromand3@mail.ru, Gender = Male
Id = 5, Full name = Maynord Herculson, Email = mherculson4@etsy.com, Gender = Bigender

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we learned:

  • Introduction to JSON
  • Sample program to understand the JSON implement in python

You can download the source code of this tutorial from the Downloads section.

5. Download the Project

This was a tutorial to understand the JSON implement in python.

Download
You can download the full source code of this example here: Python JSON Example

Last updated on Feb. 24th, 2022

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Leocadio
Leocadio
3 years ago

Good job.

Back to top button