Read, Write, Parse JSON (With Examples) (2024)

JSON (JavaScript Object Notation) is a popular data format used for representing structured data. It's common to transmit and receive data between a server and web application in JSON format.

In Python, JSON exists as a string. For example:

p = '{"name": "Bob", "languages": ["Python", "Java"]}'

It's also common to store a JSON object in a file.

Import json Module

To work with JSON (string, or file containing JSON object), you can use Python's json module. You need to import the module before you can use it.

import json

Parse JSON in Python

The json module makes it easy to parse JSON strings and files containing JSON object.

Example 1: Python JSONto dict

You can parse a JSON string using json.loads() method. The method returns a dictionary.

import jsonperson = '{"name": "Bob", "languages": ["English", "French"]}'person_dict = json.loads(person)# Output: {'name': 'Bob', 'languages': ['English', 'French']}print( person_dict)# Output: ['English', 'French']print(person_dict['languages'])

Here, person is a JSON string, and person_dict is a dictionary.

Example 2: Python read JSON file

You can use json.load() method to read a file containing JSON object.

Suppose, you have a file named person.json which contains a JSON object.

{"name": "Bob", "languages": ["English", "French"]}

Here's how you can parse this file:

import jsonwith open('path_to_file/person.json', 'r') as f: data = json.load(f)# Output: {'name': 'Bob', 'languages': ['English', 'French']}print(data)

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.

If you do not know how to read and write files in Python, we recommend you to check Python File I/O.

Python Convert to JSON string

You can convert a dictionary to JSON string using json.dumps() method.

Example 3: Convert dict to JSON

import jsonperson_dict = {'name': 'Bob','age': 12,'children': None}person_json = json.dumps(person_dict)# Output: {"name": "Bob", "age": 12, "children": null}print(person_json)

Here's a table showing Python objects and their equivalent conversion to JSON.

PythonJSON Equivalent
dictobject
list, tuplearray
strstring
int, float, intnumber
Truetrue
Falsefalse
Nonenull

Writing JSON to a file

To write JSON to a file in Python, we can use json.dump() method.

Example 4: Writing JSON to a file

import jsonperson_dict = {"name": "Bob","languages": ["English", "French"],"married": True,"age": 32}with open('person.txt', 'w') as json_file: json.dump(person_dict, json_file)

In the above program, we have opened a file named person.txt in writing mode using 'w'. If the file doesn't already exist, it will be created. Then, json.dump() transforms person_dict to a JSON string which will be saved in the person.txt file.

When you run the program, the person.txt file will be created. The file has following text inside it.

{"name": "Bob", "languages": ["English", "French"], "married": true, "age": 32}

Python pretty print JSON

To analyze and debug JSON data, we may need to print it in a more readable format. This can be done by passing additional parameters indent and sort_keys to json.dumps() and json.dump() method.

Example 5: Python pretty print JSON

import jsonperson_string = '{"name": "Bob", "languages": "English", "numbers": [2, 1.6, null]}'# Getting dictionaryperson_dict = json.loads(person_string)# Pretty Printing JSON string backprint(json.dumps(person_dict, indent = 4, sort_keys=True))

When you run the program, the output will be:

{ "languages": "English", "name": "Bob", "numbers": [ 2, 1.6, null ]}

In the above program, we have used 4 spaces for indentation. And, the keys are sorted in ascending order.

By the way, the default value of indent is None. And, the default value of sort_keys is False.

Recommended Readings:

Read, Write, Parse JSON (With Examples) (2024)

FAQs

What is the example of parsing JSON? ›

Example - Parsing JSON

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

How to read JSON file using JSON parser? ›

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.

What does the JSON parse () method? ›

JSON.parse() The JSON.parse() static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

How to convert a JSON object to string? ›

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj);

What is JSON format with example? ›

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

What is parsing explain with example? ›

"The woman with the sparkly black backpack is my sister." In this example, we can see two main constituents: the subject (The woman with the sparkly black backpack) and its predicate (is my sister). Parsing helps us to recognize which group of words is the subject and which ones are the predicate.

What is the difference between JSON and parse JSON? ›

The difference is: json() is asynchronous and returns a Promise object that resolves to a JavaScript object. JSON. parse() is synchronous can parse a string to (a) JavaScript object(s).

Why do we need to parse JSON? ›

Why use Parse JSON? The Parse JSON action in Power Automate is a powerful tool that allows you to take raw JSON output from an HTTP request for example and turn it into values that can be used as dynamic content for your flow.

How does a JSON parser work? ›

A JSON (JavaScript Object Notation) parser is a program that reads a JSON-formatted text file and converts it into a more easily usable data structure, such as a dictionary or a list in Python or an object in JavaScript.

What does JSON stand for? ›

JSON stands for JavaScript Object Notation. JSON is a lightweight format for storing and transporting data. JSON is often used when data is sent from a server to a web page.

Why is JSON better than XML? ›

JSON has smaller file sizes and faster data transmission. XML tag structure is more complex to write and read and results in bulky files. JSON is safer than XML.

How to write a JSON object? ›

JSON Object Example

The keys are strings and the values are the JSON types. Keys and values are separated by colon. Each entry (key/value pair) is separated by comma. The { (curly brace) represents the JSON object.

What is an example of data parsing? ›

For example, suppose a user views an HTML file that is likely to be challenging to read and comprehend. Data parsing will help convert that into a more readable format, such as plain text, which the viewer can easily understand.

How to solve parse error in JSON? ›

To fix a JSON parse error in Python, you should convert the objects to have a JSON-like structure, enclose keys with double quotes, replace Python constants with their JSON equivalents, strip trailing commas and comments, and concatenate strings.

What is an example of a JSON sequence? ›

array A JSON array is an ordered sequence of JSON documents separated by commas and enclosed in brackets. For example, ["Hello", 23, true, null] is a JSON array, as well as [-2, -1, 3.14, 1.62e10] . object A JSON object is a set of pairs of the form key:value , where key is a JSON string and value is a JSON document.

How to parse the JSON data to list? ›

Convert Python Json To List Using JSON.

loads()` method to convert a JSON-formatted string `[1,2,3,4]` into a Python list named `array`. The `print` statements display the type of the original string, the first element of the resulting list, and the type of the converted list, respectively.

Top Articles
API Keys / Key Rotation
Remarks at the Signing of the Excise Tax Reduction Bill
Radikale Landküche am Landgut Schönwalde
Kem Minnick Playboy
Crossed Eyes (Strabismus): Symptoms, Causes, and Diagnosis
Rondale Moore Or Gabe Davis
Category: Star Wars: Galaxy of Heroes | EA Forums
Anki Fsrs
Oscar Nominated Brings Winning Profile to the Kentucky Turf Cup
978-0137606801
Saberhealth Time Track
Tcu Jaggaer
Kitty Piggy Ssbbw
Labby Memorial Funeral Homes Leesville Obituaries
Ruse For Crashing Family Reunions Crossword
Kringloopwinkel Second Sale Roosendaal - Leemstraat 4e
Football - 2024/2025 Women’s Super League: Preview, schedule and how to watch
Bjerrum difference plots - Big Chemical Encyclopedia
Ceramic tiles vs vitrified tiles: Which one should you choose? - Building And Interiors
Redfin Skagit County
Bellin Patient Portal
eugene bicycles - craigslist
Kimoriiii Fansly
Vera Bradley Factory Outlet Sunbury Products
Pacman Video Guatemala
The Clapping Song Lyrics by Belle Stars
Frank Vascellaro
Gr86 Forums
About Us | SEIL
Mcgiftcardmall.con
Koninklijk Theater Tuschinski
Skip The Games Grand Rapids Mi
Сталь aisi 310s российский аналог
The best specialist spirits store | Spirituosengalerie Stuttgart
Tripadvisor Vancouver Restaurants
The power of the NFL, its data, and the shift to CTV
Exam With A Social Studies Section Crossword
Blue Beetle Showtimes Near Regal Evergreen Parkway & Rpx
Avatar: The Way Of Water Showtimes Near Jasper 8 Theatres
Best Haircut Shop Near Me
Europa Universalis 4: Army Composition Guide
Greg Steube Height
Xre 00251
Playboi Carti Heardle
Server Jobs Near
Rocket Bot Royale Unblocked Games 66
Ark Silica Pearls Gfi
Turning Obsidian into My Perfect Writing App – The Sweet Setup
Varsity Competition Results 2022
Latest Posts
Article information

Author: Patricia Veum II

Last Updated:

Views: 6239

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.