Comprehensive Guide to JSON Lists with Examples
Understanding JSON Lists with Examples and Code Explained
JSON (JavaScript Object Notation) is a lightweight data-interchange format, easy for humans to read and write and simple for machines to parse and generate. A JSON list is essentially an array structure that holds multiple JSON objects or values.
Syntax of JSON List:
[ { "key1": "value1", "key2": "value2" }, { "key1": "value3", "key2": "value4" } ]
- A JSON list is enclosed in square brackets [].
- Each item in the list can be a JSON object (enclosed in curly braces {}) or a simple value (e.g., string, number, boolean).
Example JSON List with Code and Explanation
Here’s an example to parse and use a JSON list in Python:
JSON List Example:
[ {"id": 1, "name": "Sara", "age": 25}, {"id": 2, "name": "Bob", "age": 30}, {"id": 3, "name": "Charlie", "age": 35} ]
Python Code to Process JSON List:
Code:
# Import the json module to work with JSON data
import json
# Define a JSON list as a string
json_data = '''
[
{"id": 1, "name": "Sara", "age": 25},
{"id": 2, "name": "Bob", "age": 30},
{"id": 3, "name": "Charlie", "age": 35}
]
'''
# Parse the JSON string into a Python list
data = json.loads(json_data) # Convert JSON string to Python objects
# Iterate over each item in the JSON list
for item in data:
# Print each person's details
print(f"ID: {item['id']}, Name: {item['name']}, Age: {item['age']}")
Output:
ID: 1, Name: Sara, Age: 25 ID: 2, Name: Bob, Age: 30 ID: 3, Name: Charlie, Age: 35
Code Explanation:
- Python’s built-in json module allows you to parse JSON data into Python objects.
- The JSON list is defined as a multi-line string using triple quotes.
- The json.loads() function parses the JSON string and converts it into a Python list of dictionaries.
- A for loop is used to iterate through the list.
- Each dictionary in the list is accessed, and its keys (id, name, age) are used to retrieve values.
- The details of each person (ID, name, age) are displayed.
1. Importing the json Module:
2. Defining JSON Data:
3. Parsing JSON String:
4. Iterating Through the List:
5. Printing Data:
Additional Notes
- Accessing Specific Elements: Use indexing to access specific items:
print(data[0]['name']) # Output: Sara
data[0]['age'] = 26 # Update Sara's age data.append({"id": 4, "name": "Diana", "age": 28}) # Add a new person
json_output = json.dumps(data, indent=4) print(json_output)
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics