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

How to read and write parse data from JSON file? ›

Example
  1. We first import the json module.
  2. The user_data dictionary holds the data we want to write to the file.
  3. We open a file named user_data. json in write mode ('w'). If the file doesn't exist, it will be created.
  4. We write the dictionary to the file using the json. dump() method.
Nov 26, 2023

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"}');

How to read a JSON format? ›

JSON files are human-readable means the user can read them easily. These files can be opened in any simple text editor like Notepad, which is easy to use. Almost every programming language supports JSON format because they have libraries and functions to read/write JSON structures.

How to parse JSON in script? ›

const json = '{"result":true, "count":42}';
  1. const obj = JSON. parse(json);
  2. console. log(obj. count); // Expected output: 42.
  3. console. log(obj. result); // Expected output: true.
Mar 17, 2024

How to parse JSON in text file? ›

If we have a JSON string, we can parse it by using the json.loads() method. json.loads() does not take the file path, but the file contents as a string, to read the content of a JSON file we can use fileobject.read() to convert the file into a string and pass it with json.loads().

What is the difference between JSON and parse JSON? ›

JSON. stringify() converts JavaScript objects or values into JSON strings, facilitating data transmission and storage. On the other hand, JSON. parse() transforms JSON strings back into JavaScript objects or values, enabling easy access and manipulation of the data.

What is the difference between JSON and parse? ›

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).

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 the correct way to write a JSON data? ›

Valid JSON data can be in two different formats: A collection of key-value pairs enclosed by a pair of curly braces {...} . You saw this as an example above. A collection of an ordered list of key-value pairs separated by comma (,) and enclosed by a pair of square brackets [...] .

How to write a JSON code? ›

JSON Syntax
  1. Always enclose the key, value pair within double quotes. Most JSON parsers don't like to parse JSON objects with single quotes. ...
  2. Never use hyphens in your key fields. Use underscores ( _ ), all lower case, or camel case. ...
  3. Use a JSON linter to confirm valid JSON.
Apr 20, 2021

How to write data in JSON file? ›

Steps
  1. We have to go through the following steps for adding the data in the data. json file using JavaScript: ...
  2. Parse the JSON data into a JavaScript object using the JSON. ...
  3. Modify the jsonData object as follows: ...
  4. Write the updated JavaScript object back to the JSON file using the writeFileSync() method as follows:

How to read the JSON response? ›

To read a JSON response there is a widely used library called urllib in python. This library helps to open the URL and read the JSON response from the web. To use this library in python and fetch JSON response we have to import the json and urllib in our code, The json. loads() method returns JSON object.

What JSON stands 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.

What is JSON formatting? ›

JSON is a human-readable format for storing and transmitting data. As the name implies, it was originally developed for JavaScript, but can be used in any language and is very popular in web applications. The basic structure is built from one or more keys and values: { "key": value }

How to convert JSON data to readable format? ›

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 read the contents of a JSON file? ›

Opening JSON files is far more straightforward than you might think; it is a very simple data structure that is entirely text-based — which is why it is limited to strings and numbers. Because of this, you can use any file opener to view a JSON file, such as notepads, text editors, and even command-line interfaces.

How to extract data from JSON format? ›

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 to read data from a JSON object? ›

getJsonObject() Method

It is used to get the (JsonObject)get(name). The method parses an argument name of type String whose related value is to be returned. It returns the object of the associated mapping for the parse's parameter.

Top Articles
Latest Posts
Article information

Author: Moshe Kshlerin

Last Updated:

Views: 6290

Rating: 4.7 / 5 (57 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Moshe Kshlerin

Birthday: 1994-01-25

Address: Suite 609 315 Lupita Unions, Ronnieburgh, MI 62697

Phone: +2424755286529

Job: District Education Designer

Hobby: Yoga, Gunsmithing, Singing, 3D printing, Nordic skating, Soapmaking, Juggling

Introduction: My name is Moshe Kshlerin, I am a gleaming, attractive, outstanding, pleasant, delightful, outstanding, famous person who loves writing and wants to share my knowledge and understanding with you.