Understanding JSON in python

Understanding JSON in python

JSON (JavaScript Object Notation) is the lightweight and widely used format for storing and exchanging the data. it is easy to read write and process, making it popular choice for web api and data storage. python provide the inbuild Json module to work with Json data efficiently.


What is JSON ?

Json represent as the key-value pairs similar to the python dictionary. It supports data types like string, numbers, Booleans, array(list), and nested objects.

Example of the JSON data:

{
    "Name" : "Yokeswaran",
    "age" : 22,
    "isEmployee" : true,
    "Skills" : ["Python","Machine learning","Artificial intelligent","Data Scientist"],
    "Adress" : {
                "Street" : "Vivekanandhapuram West",
                "Town" : "Devakottai",
                "Pincode" : 630303
    
    }        

This structure consists of:

  • Strings ("name": "Yokeswaran")
  • Numbers ("age": 22)
  • Booleans ("isEmployee": true)
  • Arrays ("Skills": ["Python","Machine learning","Artificial intelligent","Data Scientist"])
  • Nested objects ("Address": {})


JSON operation in the python

1. Reading JSON from a File: json.load()

The json.load() function is used to read JSON data from a file and convert it into a Python object (typically a dictionary).

Example:

import json

with open('data.json', 'r') as file:
    data = json.load(file)  # Reads JSON from the file and converts it into a Python dictionary

print(data)
        

In this example, the JSON file data.json is opened in read mode. The content is then converted into a Python dictionary stored in the variable data.

2. Converting JSON from a String: json.loads()

When you have a JSON-formatted string (for example, from an API response), json.loads() is used to convert the string into a Python object.

Example:

import json

json_string = '{"name": "yokeswaran", "age": 22, "is_student": false}'
data = json.loads(json_string)  # Converts the JSON string into a Python dictionary

print(data)
        

3. Writing JSON to a File: json.dump()

The json.dump() function serializes a Python object as JSON and writes it directly to a file.

Example:

import json

data = {"name": "Alice", "age": 25, "is_student": False}

with open('output.json', 'w') as file:
# Writes the Python object to a file as formatted as JSON
    json.dump(data, file, indent=4)  
        

This example shows how to write the dictionary data to output.json with proper indentation for readability.

4. Converting a Python Object to a JSON String: json.dumps()

If you need a JSON string instead of writing directly to a file, use json.dumps() to convert a Python object to a JSON-formatted string.

Example:

import json

data = {"name": "Alice", "age": 25, "is_student": False}
json_string = json.dumps(data, indent=4)  # Converts the Python object to a JSON string

print(json_string)
        

This example converts the Python dictionary into a well-formatted JSON string and prints it out.

Key Takeaways

  • json.load(): Reads JSON data from a file and converts it into a Python object.
  • json.loads(): Converts a JSON string into a Python object.
  • json.dump(): Converts a Python object into JSON format and writes it to a file.
  • json.dumps(): Converts a Python object into a JSON-formatted string.


Conclusion:

In conclusion, JSON is a lightweight data format that's easy to read and use. Python's json module provides straightforward functions to convert between JSON data and Python objects, making it simple to work with data from files or strings. Whether you're reading configuration files or handling API responses, these tools help streamline your data processing tasks.


Vaseekaran K V

Aspiring Software Developer | B.E. Computer Science, Rajalakshmi Engineering College '24 | Seeking Internship & Full-Time Opportunities

1 天前

Love this insight

回复
Vikram V

Adaptive and Aspiring software Developer | Seeking Opportunities to Innovate and Grow

2 天前

Well framed.

?? interesting

Yokesh Ramlal

Quality Assurance Engineer

3 天前

Great work ??

Yazhini S

Attended Rajalakshmi Engineering College

3 天前

Good explanation

要查看或添加评论,请登录

Yokeswaran S的更多文章

  • An In-Depth Exploration of Iterators and Generators in Python

    An In-Depth Exploration of Iterators and Generators in Python

    Iterators in Python Definition An iterator in Python is an object that allows traversal through elements of an iterable…

    8 条评论
  • Quick Revision: Essential Statistical Concepts

    Quick Revision: Essential Statistical Concepts

    Statistics is the science of collecting, analyzing, and interpreting data. This guide serves as a quick revision of key…

    7 条评论
  • Introduction to Linear transformation and application in Data science

    Introduction to Linear transformation and application in Data science

    Functions : A function is a mathematical relationship that uniquely associates element of one set (called domain) with…

    10 条评论
  • Vectors, Their Operations, and Applications in Data Science ??

    Vectors, Their Operations, and Applications in Data Science ??

    Vectors: A vectors is an ordered list of numbers. it can represent a point in space or quantify with both magnitude and…

    11 条评论
  • Why for sample variance is divided by n-1?? ??

    Why for sample variance is divided by n-1?? ??

    Unbiased Estimator ??Understanding Variance, Standard Deviation, Population, Sample, and the Importance of Dividing by…

    6 条评论
  • Confusion within the confusion matrix ????

    Confusion within the confusion matrix ????

    What is the Confusion Matrix? A confusion matrix is a table used to evaluate the performance of a classification model.…

    8 条评论
  • Outliers:

    Outliers:

    What are Outliers? ??Outliers are the data points that are significantly differ from other data points. This may arise…

    12 条评论
  • Percentile

    Percentile

    What is percentile? ?? In statistics, a percentile indicates how a particular score compares to others within the same…

    10 条评论