Back to Examples
JSON Parsing
BeginnerLearn how to parse, manipulate, and generate JSON data using Tea's built-in JSON module.
Basic JSON Parsing
parse_json.tea
import JSON
# Parse a JSON string
var json_string = '{"name": "Alice", "age": 30, "city": "NYC"}'
var data = JSON.parse(json_string)
# Access values
print("Name: ${data['name']}")
print("Age: ${data['age']}")
print("City: ${data['city']}")Output:
Name: Alice
Age: 30
City: NYCReading JSON from File
read_json_file.tea
import JSON
import File
# Read JSON from a file
var content = File.read("users.json")
var users = JSON.parse(content)
# Iterate over users
for user of users
print("User: ${user['name']}, Email: ${user['email']}")
endGenerating JSON
generate_json.tea
import JSON
# Create a data structure
var person = {
"name": "Bob",
"age": 25,
"hobbies": ["reading", "coding", "gaming"],
"address": {
"street": "123 Main St",
"city": "Boston"
}
}
# Convert to JSON string
var json_output = JSON.stringify(person, indent: 2)
print(json_output)Output:
{
"name": "Bob",
"age": 25,
"hobbies": ["reading", "coding", "gaming"],
"address": {
"street": "123 Main St",
"city": "Boston"
}
}Key Concepts
- 1JSON.parse()
Converts a JSON string into a Tea data structure (objects and arrays)
- 2JSON.stringify()
Converts Tea data structures into JSON strings, with optional formatting
- 3File Integration
Combine JSON parsing with file operations to read and write JSON files