Python Json

All tasks assume you use:

import json

πŸ“¦ Python JSON – 20 Basic Assignments


1) Import and Print json Module

Write a simple script that imports json and prints json.dumps and json.loads to verify import.


2) Convert Dict to JSON String

Create a Python dictionary like:

data = {"name": "Alice", "age": 20}

Convert it to a JSON string using json.dumps() and print.


3) Convert List to JSON

Convert the Python list:

[1, 2, 3, 4]

to JSON with json.dumps().


4) Convert JSON String to Dict

Take JSON string:

Convert it to a Python dict using json.loads() and print.


5) Write Dict to JSON File

Create a dictionary and save it to a file named data.json.


6) Read JSON from File

Read the data.json file created in #5 and print its Python object.


7) Pretty-Print JSON

Convert a dict to JSON with indentation (indent=4) and print.


8) Update Value in JSON

Given JSON string:

Convert to Python, update age to 26, and print updated dict.


9) JSON with Nested Dict

Create a nested dict:

Convert it to JSON string.


10) JSON Array to Python List

Convert JSON array:

to a Python list and print.


11) JSON with Boolean

Convert this into JSON:


12) JSON with None

Convert this Python dict to JSON:

Observe how None becomes null in JSON.


13) Validate JSON Format

Ask the user for a JSON string and use json.loads() inside a try/except to print whether it’s valid.


14) JSON Keys and Values

Given a JSON string, convert to dict and print all keys and then all values separately.

Example:


15) Nested JSON Parsing

Given nested JSON:

Convert and access the list of members.


16) Append to JSON List

Start with a JSON string representing a list:

Convert to Python list, append 4, then convert back to JSON and print.


17) Remove Key from JSON

Convert this JSON:

to dict. Remove key b, then convert back to JSON.


18) JSON Formatting Options

Convert a list of dictionaries with json.dumps(..., sort_keys=True) and print.


19) Read JSON File and Update

Read data.json, add a new key-value "updated": True, and write back to the same file.


20) Compare Two JSON Strings

Ask user for two JSON strings. Parse both and print whether they represent the same Python object.


🧠 Concepts Practiced

Topic
What You Learn

Converting Python β†’ JSON

json.dumps()

Converting JSON β†’ Python

json.loads()

File I/O with JSON

json.dump() / json.load()

Pretty JSON

indent formatting

Error handling

Catch invalid JSON

Nested structures

Read/modify nested JSON data


πŸ“Œ Starter Code Snippets

Python β†’ JSON

JSON β†’ Python

Write to File

Read from File


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated