Python JSON Tutorial Read Write

JSON, an acronym for JavaScript Object Notation, is a widely-used format for sharing data over the internet. It serves as the optimal structure for facilitating data organization between a client and a server. The syntax of JSON closely resembles that of the JavaScript programming language. The main purpose of JSON is to enable data communication between the client and the web server. It represents the most effective approach for data exchange and is easy to learn. Additionally, it is compatible with numerous programming languages, such as Python, Perl, Java, and others.

In JavaScript, JSON primarily supports the following six forms of data:

  • String
  • Number
  • Boolean
  • Null
  • Object
  • Array
  • Two Structures form the Foundation of JSON

  • Data is kept in name/value pairs. It is handled like a record, object, dictionary, hash table, or keyed list.
  • An array, vector, list, or sequence is all considered equivalent to the ordered list of values.

The Python dictionary can be likened to the JSON data format. Below is an example of JSON data:

Example

{

 "book": [

  {

       "id": 01,

"language": "English",

"edition": "Second",

"author": "Derrick Mwiti"

],

   {

  {

    "id": 02,

"language": "French",

"edition": "Third",

"author": "Vladimir"

}

}

Utilizing Python JSON

JSON is a module provided by Python. In addition to JSON, Python includes the marshal and pickle modules as part of its standard library, and the JSON API operates in a manner akin to these libraries. Python inherently accommodates the features of JSON.

The act of converting JSON data into a serialized format is referred to as encoding. Through this serialization method, information is converted into a sequence of bytes that can be transmitted over the network.

Example

import json

print(dir(json))

Output:

Output

['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', '--all--', '--author--', '--builtins--', '--cached--', '--doc--', '--file--', '--loader--', '--name--', '--package--', '--path--', '--spec--', '--version--', '-default-decoder', '-default-encoder', 'codecs', 'decoder', 'detect-encoding', 'dump', 'dumps', 'encoder', 'load', 'loads', 'scanner']

The following techniques will be covered in this section:

  • load
  • loads
  • dump
  • dumps
  • Serializing JSON

The technique employed to convert Python objects into JSON format is referred to as serialization. When a system is required to handle large volumes of data, it is advisable to save that data into a file. By utilizing the JSON functionality, we can write JSON data into a file. The methods dump and dumps can be found within the json module and are utilized for manipulating Python objects.

The JSON items listed below have been generated from Python objects. Here is a compilation of each item:

Sr. Python Objects JSON
1. Dict Object
2. list, tuple Array
3. Str String
4. int, float Number
5. True true
6. False false
7. None null

The writing of JSON data into a file function dump

In Python, the dump function is utilized to encode data into JSON format. This function requires two positional parameters: the data structure that is to be serialized and a file-like object that will accept the resulting byte stream.

Let’s examine a simple example of serialization:

Example

import json

# Key:value mapping

student = {

    "Name": "Peter",

    "Roll-no": "0090014",

    "Grade": "A",

    "Age": 20,

    "Subject": ["Computer Graphics", "Discrete Mathematics", "Data Structure"]

}

# Writing JSON data to a file

with open("data.json", "w") as write-file:

    json.dump(student, write-file, indent=4)

# Display JSON on the screen

print(json.dumps(student, indent=4))

Output:

Output

{

    "Name": "Peter",

    "Roll-no": "0090014",

    "Grade": "A",

    "Age": 20,

    "Subject": [

        "Computer Graphics",

        "Discrete Mathematics",

        "Data Structure"

    ]

}

Explanation:

In the preceding program, a file named data.json has been accessed in write mode. This approach was adopted to ensure the file is generated if it is not already present. The dictionary is transformed into a JSON formatted string through the utilization of the json.dump function.

The function dumps

The serialized information is stored within the Python script through the use of the dumps function. This function requires a single argument, which is the Python data that needs to be serialized. Since we are not writing the data to a disk, the file-like parameter is unnecessary. Consider the following example:

Example

import json

# Key:value mapping

student  = {

"Name" : "Peter",

"Roll-no" : "0090014",

"Grade" : "A",

"Age": 20

}

b = json.dumps(student)

print(b)

Output:

Output

{"Name": "Peter", "Roll-no": "0090014", "Grade": "A", "Age": 20}

JSON supports hierarchical structures including lists, tuples, objects, as well as fundamental data types such as strings and numbers.

Example

import json

#Python  list conversion to JSON  Array

print(json.dumps(['Welcome', "to", "Example"]))

#Python  tuple conversion to JSON Array

print(json.dumps(("Welcome", "to", "Example")))

# Python string conversion to JSON String

print(json.dumps("Hello"))

# Python int conversion to JSON Number

print(json.dumps(1234))

# Python float conversion to JSON Number

print(json.dumps(23.572))

# Boolean conversion to their respective values

print(json.dumps(True))

print(json.dumps(False))

# None value to null

print(json.dumps(None))

Output:

Output

["Welcome", "to", "Example"]

["Welcome", "to", "Example"]

"Hello"

1234

23.572

true

false

null

JSON Deserialization

The act of transforming JSON data into Python objects is referred to as deserialization. The json module provides two methods, load and loads, which facilitate this conversion from JSON format to Python objects. Below is a detailed list of each method:

SR. JSON Python
1. Object dict
2. Array list
3. String str
4. number(int) int
5. true True
6. false False
7. null None

Although technically not a precise conversion of the JSON data, the above table depicts the opposite of the serialized table. This indicates that the object may not be the same if we encode it and then decode it again later.

Let’s consider a practical example. When an individual translates text into Chinese and subsequently translates it back into English, the resulting translation might not accurately reflect the original content. Use this simple scenario as a demonstration.

Example

import json

a = (10,20,30,40,50,60,70)

print(type(a))

b = json.dumps(a)

print(type(json.loads(b)))

Output:

Output

<class 'tuple'>

<class 'list'>

load Method

The JSON information retrieved from the file is converted into a Python object through the utilization of the load function. To illustrate the use of the load method in Python, let us consider an example.

Example

import json

# Key:value mapping

student  = {

"Name" : "Peter",

"Roll-no" : "0090014",

"Grade" : "A",

"Age": 20,

}

with open("data.json","w") as write-file:

    json.dump(student,write-file)

with open("data.json", "r") as read-file:

    b = json.load(read-file)

print(b)

Output:

Output

{'Name': 'Peter', 'Roll-no': '0090014', 'Grade': 'A', 'Age': 20}

By utilizing the dump function, we have serialized a Python object into a file as shown in the previous program. Subsequently, we access the JSON file through the load function, supplying the argument read-file.

The loads method, which is another capability of the json module, serves the purpose of converting JSON input into Python objects. It is quite similar to the load function. Consider the following example:

Example

import json

a = ["Mathew","Peter",(10,32.9,80),{"Name" : "Tokyo"}]

# Python object into JSON

b = json.dumps(a)

# JSON into Python Object

c = json.loads(b)

print(c)

Output:

Output

['Mathew', 'Peter', [10, 32.9, 80], {'Name': 'Tokyo'}]

json.load vs json.loads

JSON files can be imported into a program utilizing the json.load method, whereas JSON strings are imported through the json.loads method.

json.dump vs json.dumps

To convert Python objects into JSON files, we employ the json.dump function. Additionally, we make use of the JSON.dumps function to convert JSON data into a string format, which can then be processed or printed.

Python Pretty Print JSON

In certain situations, extensive JSON data requires analysis and debugging. This can be accomplished by passing additional parameters to the json.dumps and json.dump functions, including options like indent and sort_keys.

Note: Both dump and dumps functions accept indent and short-keys arguments.

Consider the following example:

Example

import json

person = '{"Name": "Abdul","City":"English", "Number":90014, "Age": 23,"Subject": ["Data Structure","Computer Graphics", "Discrete mathematics"]}'

per-dict = json.loads(person)

print(json.dumps(per-dict, indent = 5, sort-keys= True))

Output:

Output

{

"Age": 23,

"City": "English",

"Name": "Abdul",

"Number": 90014,

"Subject": [

"Data Structure",

"Computer Graphics",

"Discrete mathematics"

]

}

Explanation:

The keys are arranged in increasing order, and the indent parameter in the aforementioned code is set to five spaces. The default setting for sort-key is False, while the default value for indent is None.

Coding and Decoding

The act of transforming text or values into a secure format is referred to as encoding. Once transformed, only the designated user has the ability to access the encrypted data through the process of decoding. Encoding is often synonymous with serialization, while decoding can also be described as deserialization. In the context of the JSON(object) format, both encoding and decoding procedures take place. Python provides a widely-used module to facilitate these operations. To install it on a Windows system, you can use the following command:

Example

pip install json

Encoding

The encode method, included in the demon package, serves the purpose of converting a Python object into its corresponding JSON string format.

Example: Encoding using the JSON package

Example

import json

a = [{"Name": "Peter", "Age": 20, "Subject": "Electronics"}]

# Convert Python object to JSON string

print(json.dumps(a, indent=4))

Output:

Output

[

    {

        "Name": "Peter",

        "Age": 20,

        "Subject": "Electronics"

    }

]

Decoding

The decode method found in the demon module serves the purpose of converting JSON objects into their corresponding Python data types.

Example

import json

a = "['Peter', 'Smith', 'Ricky', 'Hayden']"

print(json.dumps(a))

Output:

Output

['Peter', 'Smith', 'Ricky', 'Hayden']

In this guide, we have explored the concept of Python JSON. JSON serves as the most efficient method for transferring data between a client and a web server.

Python JSON FAQs

1. What is JSON in Python?

JSON, an abbreviation for JavaScript Object Notation, is a widely used data format for the exchange of information over the internet. It is regarded as the optimal format for structuring data communication between a client and a server.

2. How can we import the JSON module?

We can import the JSON module by:

Example

import json

3. How can we convert a Python dictionary to JSON?

To transform a Python dictionary into JSON format, we can utilize the dumps function. Let's illustrate this with an example:

Example:

Example

import json

data = {"name": "Example", "age": 14}

json-str = json.dumps(data)

print(json-str)

Output:

Output

{"name": "Example", "age": 14}

4. How can we convert a JSON string to a Python dictionary?

We can transform a JSON string into a Python Dictionary by utilizing the loads function. Let’s illustrate this with an example:

Example:

Example

json-str = '{"name": "Example", "age": 14}'

data = json.loads(json-str)

print(data["name"])

Output:

Output

Example

5. What is the difference between json.load and json.loads?

The primary distinction between json.load and json.loads lies in their input sources:

  • load: The json.load function retrieves JSON data from a file-like object.
  • loads: The json.loads function extracts JSON data from a string format.

Input Required

This code uses input(). Please provide values below: