Big Idea 3 - Unit 2
π October 11, 2024
π Summary
This lesson expands on variable types introduced earlier and introduces JSON (JavaScript Object Notation), a format commonly used for storing and exchanging data.
Core Data Types:
String
: text in quotes ("hello"
)Integer
: whole numbers (42
)Float
: decimal numbers (3.14
)Boolean
:True
/False
Array/List
: ordered collections of itemsObject/Dictionary
: key-value pairs
What is JSON?
JSON is a lightweight data format, similar to Python dictionaries or JavaScript objects. Itβs used for sending structured data, especially in APIs.
Scroll down for Python and JavaScript examples + a JSON-based homework exercise.
import json
honda_civic = {
"name": "Honda Civic",
"performance": {
"engine": "2.0-liter 4-cylinder",
"horsepower": 158,
"top_speed": "200 km/h",
"acceleration": "0 to 100 km/h in 8.2 seconds"
},
"features": {
"driving_assistance": "Honda Sensing suite with adaptive cruise control and lane-keeping assist",
"exterior": "modern, aerodynamic design",
"interior": "spacious with durable cloth or optional leather seats"
},
"pricing": {
"original_price": "$24,000",
"production_run": "ongoing",
"rarity": "widely available"
}
}
# Convert Python dictionary to JSON string
jsonstring = json.dumps(honda_civic, indent=2)
print(jsonstring)
import requests
url = "https://jsonplaceholder.typicode.com/posts"
response = requests.get(url)
if response.status_code == 200:
data = response.json() # Convert response to JSON
print("Original Data:", data[0]) # Preview the first post
# Modify data
data[0]["title"] = "yay" # String
data[0]["likes"] = 0 # Integer
data[0]["rating"] = 3.5 # Float
data[0]["tags"] = ["fun", "more fun"] # List
data[0]["is_active"] = True # Boolean
print("\nModified Data for Post ID 1:")
print(data[0])
else:
print("Failed to retrieve data")
let response1 = true;
console.log("A squirrel will steal your button: " + response1);
let response2 = false;
console.log("You will be judged by a talking potato with googly eyes: " + response2);
async function fetchAndModifyData() {
const url = "https://jsonplaceholder.typicode.com/posts";
try {
const response = await fetch(url);
if (response.ok) {
const data = await response.json();
console.log("Original Data:", data[0]);
// Modify fields
data[0].title = "yay";
data[0].likes = 0;
data[0].rating = 3.5;
data[0].tags = ["fun", "more fun"];
data[0].is_active = true;
console.log("\nModified Data for Post ID 1:");
console.log(data[0]);
} else {
console.error("Failed to retrieve data.");
}
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchAndModifyData();