Extra 5% OFF Use Code: OL05
Free Shipping over β‚Ή999

JSON

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data format used to store and exchange data.

βœ… It’s like a Python dictionary, but in string form.

Python and JSON

Python has a built-in module called json that allows you to work with JSON data.

➀ Import the module:

import json

βœ… 1. Convert Python to JSON (Serialize)

➀ json.dumps()

Converts Python objects (like dict, list) β†’ JSON string.

import json

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

json_data = json.dumps(data)
print(json_data)

πŸ–¨ Output:

{"name": "Alice", "age": 25, "is_student": false}

βœ… 2. Convert JSON to Python (Deserialize)

➀ json.loads()

Converts JSON string β†’ Python object.

import json

json_string = '{"name": "Bob", "age": 30, "is_student": true}'

data = json.loads(json_string)
print(data["name"])  # Output: Bob

βœ… 3. Read from a JSON file

import json

with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)

βœ… 4. Write to a JSON file

import json

data = {
    "name": "Charlie",
    "city": "New York"
}

with open('data.json', 'w') as file:
    json.dump(data, file)

πŸ” Summary Table

FunctionPurpose
json.dumps()Python β†’ JSON string
json.loads()JSON string β†’ Python object
json.dump()Write JSON to a file
json.load()Read JSON from a file

    Leave a Reply

    Your email address will not be published.

    Need Help?