Python Parse JSON – How to Read a JSON File (2024)

/ #Python
Python Parse JSON – How to Read a JSON File (1)
Jessica Wilkins
Python Parse JSON – How to Read a JSON File (2)

JSON (JavaScript Object Notation) is a popular way to structure data. It's used to exchange information between a web application and the server. But how do you read a JSON file in Python?

In this article, I will show you how to use the json.loads() and json.load() methods to parse and read JSON files and strings.

JSON syntax

Before we get into parsing and reading a JSON file, we first need to understand the basic syntax. The JSON syntax looks like a JavaScript object literal with key-value pairs.

This is an example of JSON data for freeCodeCamp:

{ "organization": "freeCodeCamp", "website": "https://www.freecodecamp.org/", "formed": 2014, "founder": "Quincy Larson", "certifications": [ { "name": "Responsive Web Design", "courses": [ "HTML", "CSS" ] }, { "name": "JavaScript Algorithms and Data Structures", "courses": [ "JavaScript" ] }, { "name": "Front End Development Libraries", "courses": [ "Bootstrap", "jQuery", "Sass", "React", "Redux" ] }, { "name": "Data Visualization", "courses": [ "D3" ] }, { "name": "Relational Database Course", "courses": [ "Linux", "SQL", "PostgreSQL", "Bash Scripting", "Git and GitHub", "Nano" ] }, { "name": "Back End Development and APIs", "courses": [ "MongoDB", "Express", "Node", "NPM" ] }, { "name": "Quality Assurance", "courses": [ "Testing with Chai", "Express", "Node" ] }, { "name": "Scientific Computing with Python", "courses": [ "Python" ] }, { "name": "Data Analysis with Python", "courses": [ "Numpy", "Pandas", "Matplotlib", "Seaborn" ] }, { "name": "Information Security", "courses": [ "HelmetJS" ] }, { "name": "Machine Learning with Python", "courses": [ "Machine Learning", "TensorFlow" ] } ]}

How to parse a JSON string in Python

Python has a built in module that allows you to work with JSON data. At the top of your file, you will need to import the json module.

import json

If you need to parse a JSON string that returns a dictionary, then you can use the json.loads() method.

import json# assigns a JSON string to a variable called jess jess = '{"name": "Jessica Wilkins", "hobbies": ["music", "watching TV", "hanging out with friends"]}'# parses the data and assigns it to a variable called jess_dictjess_dict = json.loads(jess)# Printed output: {"name": "Jessica Wilkins", "hobbies": ["music", "watching TV", "hanging out with friends"]}print(jess_dict)

How to parse and read a JSON file in Python

In this example, we have a JSON file called fcc.json which holds the same data from earlier concerning the courses offered by freeCodeCamp.

If we want to read that file, we first need to use Python's built in open() function with the mode of read. We are using the with keyword to make sure that the file is properly closed.

with open('fcc.json', 'r') as fcc_file:

If the file cannot be opened, then we will receive an OSError. This is an example of a "FileNotFoundError" if I misspell the fcc.json file name.

Python Parse JSON – How to Read a JSON File (3)

We can then parse the file using the json.load() method and assign it to a variable called fcc_data.

 fcc_data = json.load(fcc_file)

The final step would be to print the results.

print(fcc_data)

This is what the entire code would look like:

import jsonwith open('fcc.json', 'r') as fcc_file: fcc_data = json.load(fcc_file) print(fcc_data)

How to Pretty Print JSON data in Python

If we examine the printed data, then we should see that the JSON data prints all on one line.

Python Parse JSON – How to Read a JSON File (4)

But that can be hard to read. To fix that, we can use the json.dumps() method with the parameter of indent.

In this example, we are going to have an indent of 4 spaces and print the data in an easier to read format.

 print(json.dumps(fcc_data, indent=4))
Python Parse JSON – How to Read a JSON File (5)

We can also sort the keys in alphabetical order using the sort_keys parameter and setting that to True.

print(json.dumps(fcc_data, indent=4, sort_keys=True))
Python Parse JSON – How to Read a JSON File (6)

Conclusion

JSON (JavaScript Object Notation) is a popular way to structure data and is used to exchange information between a web application and the server.

If you need to parse a JSON string that returns a dictionary, then you can use the json.loads() method.

If you need to parse a JSON file that returns a dictionary, then you can use the json.load() method.

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

Python Parse JSON – How to Read a JSON File (7)
Jessica Wilkins

I am a musician and a programmer.

If you read this far, thank the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTIsem*nT

Python Parse JSON – How to Read a JSON File (2024)

FAQs

Python Parse JSON – How to Read a JSON File? ›

Python has a built in module that allows you to work with JSON data. At the top of your file, you will need to import the json module. If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method.

How to read JSON file with JSON in Python? ›

It's pretty easy to load a JSON object in Python. Python has a built-in package called JSON, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.

How to read JSON file as JSON in Python? ›

Python has a built-in module called json for encoding and decoding JSON data. One of the most commonly used functions from this module is json. load() . This function reads a file containing JSON object and returns a Python object.

How to access JSON data from JSON file? ›

Follow these steps to read the JSON file using the fetch API method:
  1. Create a JSON file and add data to it.
  2. Open the JavaScript file.
  3. In the fetch method pass the path of the JSON file.
  4. Use the . json() method to parse the data in JSON format.
  5. Display the content in the console.
Feb 23, 2024

How to extract data from a JSON file using Python? ›

Open the JSON file in read-only mode using the Python with() function. Load the JSON data into a variable using the Python load() function. Now, get the value of keys in a variable. Now convert the value of the dictionary into a list and slice the string using the split function.

How to view JSON file in JSON format? ›

To view a JSON file stored on your device as reformatted JSON:
  1. Open a new tab or window in Microsoft Edge.
  2. Press Ctrl+O on Windows and Linux, or Command+O on macOS, and then select a JSON file.
  3. Microsoft Edge detects that the file contains JSON data and formats it automatically:

How to read a nested JSON file in Python? ›

Below are some of the ways by which we can parse nested JSON in Python:
  1. Using the JSON module.
  2. Using Recursion.
  3. Using the Pandas library.
Mar 7, 2024

How to extract a JSON file? ›

Alternatively, you can employ a command-line tool or script such as jq to quickly and easily filter, query, or transform JSON data. Additionally, you can use a graphical user interface (GUI) tool or application like Postman to visually explore, edit, and extract data from JSON files.

How do I convert a JSON file to readable? ›

You can convert JSON to TXT with MConverter in three easy steps:
  1. Choose JSON files from your device. At the top of this page, drag and drop your JSONs. ...
  2. Click or tap on TXT from the list of target formats. ...
  3. Download your TXT files, after MConverter has finished processing them.

How to convert JSON to readable format in Python? ›

We can use the dumps() method to get the pretty formatted JSON string.
  1. Python Pretty Print JSON String. import json json_data = '[{"ID":10,"Name":"Pankaj","Role":"CEO"},' \ '{"ID":20,"Name":"David Lee","Role":"Editor"}]' json_object = json. ...
  2. Python Pretty Print JSON File.

How to access JSON data in Python? ›

To read JSON data, you can use the built-in json module (JSON Encoder and Decoder) in Python. The json module provides two methods, loads and load, that allow you to parse JSON strings and JSON files, respectively, to convert JSON into Python objects such as lists and dictionaries.

How to access JSON parse data? ›

Try it
  1. const obj = JSON. parse(json);
  2. console. log(obj. count);
  3. console. log(obj. result);
Mar 17, 2024

How do I extract data from a file in Python? ›

Intro
  1. Create a function that gets a list of all files in a given directory.
  2. Extract the file name, path, size, and creation date of every file, and put this info into a list.
  3. Output the list into a readable JSON format.
Feb 12, 2023

How to write a JSON response to a file in Python? ›

JSON can also be written to a file using the json. dump() method. Without first converting the dictionary into a JSON object, the "dump" function of the JSON package simply writes the dictionary to a file in the JSON format.

What does JSON() do in Python? ›

json() is widely used to fetch data from APIs. In this article, we will explore how to use response. json() to load JSON data into Python objects.

How to get values from a JSON array in Python? ›

Get all keys and values from json object in Python
  1. {"emp_details":[ {"name": "a", "id": "123" }, {"name":"b", "id":"345" } ] } You need to give the file name, so this is my file name. ...
  2. data = json. load(jsonFile) ...
  3. jsonData = data["emp_details"] keys = x. ...
  4. import json with open("test.json") as jsonFile: data = json.
Jan 12, 2021

How to edit a JSON file in Python? ›

Modify JSON Fields Using update() Method

In this example, below code parses a sample JSON data string representing a person's information, changes the 'name' field from “Eva” to “Sophia,” and then converts the modified data back to JSON format. The resulting JSON, with the updated name, is printed to the console.

Top Articles
Investing: Risk and return (article) | Khan Academy
Investment portfolios: Asset allocation models | Vanguard
Walgreens Boots Alliance, Inc. (WBA) Stock Price, News, Quote & History - Yahoo Finance
Sprinter Tyrone's Unblocked Games
Metallica - Blackened Lyrics Meaning
4-Hour Private ATV Riding Experience in Adirondacks 2024 on Cool Destinations
Unity Stuck Reload Script Assemblies
Booknet.com Contract Marriage 2
Ofw Pinoy Channel Su
Fusion
P2P4U Net Soccer
No Credit Check Apartments In West Palm Beach Fl
New Mexico Craigslist Cars And Trucks - By Owner
Beau John Maloney Houston Tx
Red Tomatoes Farmers Market Menu
Used Drum Kits Ebay
DoorDash, Inc. (DASH) Stock Price, Quote & News - Stock Analysis
Vermont Craigs List
Walgreens Alma School And Dynamite
Atdhe Net
Happy Life 365, Kelly Weekers | 9789021569444 | Boeken | bol
Stoney's Pizza & Gaming Parlor Danville Menu
Dark Entreaty Ffxiv
eugene bicycles - craigslist
2021 MTV Video Music Awards: See the Complete List of Nominees - E! Online
Is Poke Healthy? Benefits, Risks, and Tips
Evil Dead Rise Ending Explained
Chelsea Hardie Leaked
UAE 2023 F&B Data Insights: Restaurant Population and Traffic Data
LG UN90 65" 4K Smart UHD TV - 65UN9000AUJ | LG CA
A Plus Nails Stewartville Mn
Gyeon Jahee
Craigslist Albany Ny Garage Sales
Indiana Wesleyan Transcripts
Mistress Elizabeth Nyc
Timberwolves Point Guard History
2007 Peterbilt 387 Fuse Box Diagram
Seminary.churchofjesuschrist.org
Mugshots Journal Star
Clausen's Car Wash
Windshield Repair & Auto Glass Replacement in Texas| Safelite
Sallisaw Bin Store
Craigslist Minneapolis Com
2013 Honda Odyssey Serpentine Belt Diagram
Tom Kha Gai Soup Near Me
Holzer Athena Portal
John Wick: Kapitel 4 (2023)
Zeeks Pizza Calories
Ssss Steakhouse Menu
The Missile Is Eepy Origin
Bumgarner Funeral Home Troy Nc Obituaries
Latest Posts
Article information

Author: The Hon. Margery Christiansen

Last Updated:

Views: 6473

Rating: 5 / 5 (70 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: The Hon. Margery Christiansen

Birthday: 2000-07-07

Address: 5050 Breitenberg Knoll, New Robert, MI 45409

Phone: +2556892639372

Job: Investor Mining Engineer

Hobby: Sketching, Cosplaying, Glassblowing, Genealogy, Crocheting, Archery, Skateboarding

Introduction: My name is The Hon. Margery Christiansen, I am a bright, adorable, precious, inexpensive, gorgeous, comfortable, happy person who loves writing and wants to share my knowledge and understanding with you.