Header Ads Widget

Ticker

6/random

Python JSON

Python JSON


In Python, the `json` module provides methods for working with JSON (JavaScript Object Notation) data. JSON is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. 


Here's an explanation with examples:


1. Encoding (Python to JSON):


```python

import json


# Creating a Python dictionary

person = {

    "name": "Alice",

    "age": 30,

    "city": "Wonderland"

}


# Encoding the dictionary to JSON

json_data = json.dumps(person, indent=2)


# Printing the JSON data

print(json_data)

```


The `json.dumps()` function converts a Python object (in this case, a dictionary) to a JSON formatted string.


2. Decoding (JSON to Python):


```python

import json


# JSON data as a string

json_data = '{"name": "Bob", "age": 25, "city": "Cityville"}'


# Decoding JSON to a Python dictionary

person = json.loads(json_data)


# Accessing values in the dictionary

print(person["name"], person["age"], person["city"])

```


The `json.loads()` function converts a JSON formatted string to a Python object (in this case, a dictionary).


3. Reading and Writing JSON Files:


```python

import json


# Writing JSON to a file

person = {"name": "Charlie", "age": 35, "city": "Metropolis"}

with open("person.json", "w") as json_file:

    json.dump(person, json_file, indent=2)


# Reading JSON from a file

with open("person.json", "r") as json_file:

    loaded_person = json.load(json_file)


print(loaded_person)

```


The `json.dump()` function writes a Python object to a file in JSON format, and `json.load()` reads a JSON file and converts it to a Python object.


4. Handling Custom Objects:


```python

import json


class Person:

    def __init__(self, name, age, city):

        self.name = name

        self.age = age

        self.city = city


# Encoding custom objects

person_object = Person(name="David", age=40, city="Utopia")

json_data = json.dumps(person_object, default=lambda obj: obj.__dict__)


# Decoding JSON to custom objects

loaded_person = json.loads(json_data, object_hook=lambda d: Person(**d))


print(loaded_person.name, loaded_person.age, loaded_person.city)

```


For encoding and decoding custom objects, you can use the `default` and `object_hook` parameters to specify custom serialization and deserialization methods.


The `json` module in Python is a convenient way to work with JSON data, making it easy to encode and decode data for interchange with other systems or for storing configuration information.

Post a Comment

0 Comments