Read, Write and Parse JSON using Python - GeeksforGeeks (2024)

Last Updated : 07 Aug, 2023

Summarize

Comments

Improve

JSON is a lightweight data format for data interchange that can be easily read and written by humans, and easily parsed and generated by machines. It is a complete language-independent text format. To work with JSON data, Python has a built-in package called JSON.

Example of JSON String

s = '{"id":01, "name": "Emily", "language": ["C++", "Python"]}'

The syntax of JSON is considered a subset of the syntax of JavaScript including the following:

  • Name/Value pairs: Represents Data, the name is followed by a colon(:), and the Name/Value pairs are separated by a comma(,).
  • Curly braces: Holds objects.
  • Square brackets: Hold arrays with values separated by a comma (,).

Keys/Name must be strings with double quotes and values must be data types amongst the following:

  • String
  • Number
  • Object (JSON object)
  • array
  • Boolean
  • Null

Example of JSON file:

 {
"employee": [
{
"id": "01",
"name": "Amit",
"department": "Sales"
},
{
"id": "04",
"name": "sunil",
"department": "HR"
}
]
}

Python Parse JSON String

In the below code, we are going to convert JSON to a Python object. To parse JSON string Python firstly we import the JSON module. We have a JSON string stored in a variable ’employee’ and we convert this JSON string to a Python object using json.loads() method of JSON module in Python. After that, we print the name of an employee using the key ‘name’ .

Python3

# Python program to convert JSON to Python

import json

# JSON string

employee ='{"id":"09", "name": "Nitin", "department":"Finance"}'

# Convert string to Python dict

employee_dict = json.loads(employee)

print(employee_dict)

print(employee_dict['name'])

Output

{'id': '09', 'name': 'Nitin', 'department': 'Finance'}Nitin

Python read JSON file

Let’s suppose we have a JSON file that looks like this.

Read, Write and Parse JSON using Python - GeeksforGeeks (1)

Here, we have used the open() function to read the JSON file. Then, the file is parsed using json.load() method which gives us a dictionary named data.

Python3

import json

# Opening JSON file

f = open('data.json',)

# returns JSON object as

# a dictionary

data = json.load(f)

# Iterating through the json

# list

for i in data['emp_details']:

print(i)

# Closing file

f.close()

Output:

Read, Write and Parse JSON using Python - GeeksforGeeks (2)

Convert Python Dict to JSON

In the below code, we are converting a Python dictionary to a JSON object using json.dumps() method of JSON module in Python. We first import the JSON module and then make a small dictionary with some key-value pairs and then passed it into json.dumps() method with ‘indent=4’ to convert this Python dictionary into a JSON object. As we have given the value of indent to 4 there are four whitespaces before each data as seen in the output.

Python3

# Python program to convert

# Python to JSON

import json

# Data to be written

dictionary = {

"id": "04",

"name": "sunil",

"department": "HR"

}

# Serializing json

json_object = json.dumps(dictionary, indent = 4)

print(json_object)

Output

{ "id": "04", "name": "sunil", "department": "HR"}

The following types of Python objects can be converted into JSON strings:

  • dict
  • list
  • tuple
  • string
  • int
  • float
  • True
  • False
  • None

Python objects and their equivalent conversion to JSON:

Python

JSON Equivalent

dict

object

list, tuple

array

str

string

int, float

number

True

true

False

false

None

null

Writing JSON to a file in Python

We can write JSON to file using json.dump() function of JSON module and file handling in Python. In the below program, we have opened a file named sample.json in writing mode using ‘w’. The file will be created if it does not exist. Json.dump() will transform the Python dictionary to a JSON string and it will be saved in the file sample.json.

Python3

# Python program to write JSON

# to a file

import json

# Data to be written

dictionary ={

"name" : "sathiyajith",

"rollno" : 56,

"cgpa" : 8.6,

"phonenumber" : "9976770500"

}

with open("sample.json", "w") as outfile:

json.dump(dictionary, outfile)

Output:

Read, Write and Parse JSON using Python - GeeksforGeeks (3)

Python Pretty Print JSON

When we convert a string to JSON the data is in a less readable format. To make it more readable we can use pretty printing by passing additional arguments in json.dumps() function such as indent and sort_keys as used in the below code.

Python3

# Python program to convert JSON to Python

import json

# JSON string

employee ='{"id":"09", "name": "Nitin", "department":"Finance"}'

# Convert string to Python dict

employee_dict = json.loads(employee)

# Pretty Printing JSON string back

print(json.dumps(employee_dict, indent = 4, sort_keys= True))

Output

{ "department": "Finance", "id": "09", "name": "Nitin"}


S

soumya08

Read, Write and Parse JSON using Python - GeeksforGeeks (4)

Improve

Next Article

Read and Write TOML Files Using Python

Please Login to comment...

Read, Write and Parse JSON using Python - GeeksforGeeks (2024)
Top Articles
Post-it Maker 3M Raises Annual Outlook After Q2 Beat, Stock Soars
voo stock price prediction 2030
Fiskars X27 Kloofbijl - 92 cm | bol
Bubble Guppies Who's Gonna Play The Big Bad Wolf Dailymotion
Calvert Er Wait Time
855-392-7812
Kaydengodly
Booknet.com Contract Marriage 2
Ixl Elmoreco.com
Fully Enclosed IP20 Interface Modules To Ensure Safety In Industrial Environment
Nordstrom Rack Glendale Photos
Pickswise the Free Sports Handicapping Service 2023
3656 Curlew St
Discover Westchester's Top Towns — And What Makes Them So Unique
Alaska: Lockruf der Wildnis
Nwi Arrests Lake County
Samantha Lyne Wikipedia
Michigan cannot fire coach Sherrone Moore for cause for known NCAA violations in sign-stealing case
Vermont Craigs List
Band Of Loyalty 5E
Schedule 360 Albertsons
Faurot Field Virtual Seating Chart
Dr Ayad Alsaadi
2021 Volleyball Roster
Sec Baseball Tournament Score
Best Sports Bars In Schaumburg Il
Bay Area Craigslist Cars For Sale By Owner
2011 Hyundai Sonata 2 4 Serpentine Belt Diagram
Marilyn Seipt Obituary
The Powers Below Drop Rate
Annapolis Md Craigslist
Housing Assistance Rental Assistance Program RAP
Nicole Wallace Mother Of Pearl Necklace
Σινεμά - Τι Ταινίες Παίζουν οι Κινηματογράφοι Σήμερα - Πρόγραμμα 2024 | iathens.gr
Craigslist West Seneca
42 Manufacturing jobs in Grayling
Shih Tzu dogs for sale in Ireland
Bismarck Mandan Mugshots
When His Eyes Opened Chapter 2048
The Transformation Of Vanessa Ray From Childhood To Blue Bloods - Looper
D-Day: Learn about the D-Day Invasion
Legit Ticket Sites - Seatgeek vs Stubhub [Fees, Customer Service, Security]
Flipper Zero Delivery Time
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
Mathews Vertix Mod Chart
Sacramentocraiglist
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Home | General Store and Gas Station | Cressman's General Store | California
Where Is Darla-Jean Stanton Now
Hcs Smartfind
Https://Eaxcis.allstate.com
Latest Posts
Article information

Author: Annamae Dooley

Last Updated:

Views: 6340

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Annamae Dooley

Birthday: 2001-07-26

Address: 9687 Tambra Meadow, Bradleyhaven, TN 53219

Phone: +9316045904039

Job: Future Coordinator

Hobby: Archery, Couponing, Poi, Kite flying, Knitting, Rappelling, Baseball

Introduction: My name is Annamae Dooley, I am a witty, quaint, lovely, clever, rich, sparkling, powerful person who loves writing and wants to share my knowledge and understanding with you.