Fall 2024 - P5
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.2 - Data Abstraction | JSON
Nolan & Jacob's Data Abstraction Presentation
from IPython.core.display import HTML; set_custom_css = lambda: HTML('<style>:root {--light-pink: #ffccdd; --medium-pink: #ff66b3; --dark-pink: #ff3385; --accent-pink: #ff99cc; --background-pink: #ffe6f0;} body {background-color: var(--background-pink) !important; color: var(--dark-pink) !important;} article {background-color: var(--light-pink) !important; color: var(--dark-pink) !important; border: 2px solid var(--medium-pink) !important; padding: 20px !important; border-radius: 8px !important;} a {color: var(--accent-pink) !important;} a:hover {color: var(--dark-pink) !important;} h1, h2, h3, h4 {color: white !important;} blockquote {background-color: #272726 !important; border-left: 4px solid var(--medium-pink) !important; color: var(--dark-pink) !important; padding: 10px 20px !important; margin: 10px 0 !important; border-radius: 4px !important;} code {background-color: var(--accent-pink) !important; color: white !important; padding: 2px 4px !important; border-radius: 4px !important;} .site-nav {background-color: var(--medium-pink) !important;} table td {background-color: var(--dark-pink) !important;}</style>'); set_custom_css()
3.2.1 | 3.2.2 | 3.2.3 |
Using JSON
JSON = JavaScript Object Notation.
Similar (almost the same) as a dict
. Used to store and transfer data easily, this is the form of data transferred in most APIs (99.99999%)
Python to JSON
import json # make sure to import this or it will break ur code
# dict
mercedes_clr_gtr = {
"name": "Mercedes CLR GTR",
"performance": {
"engine": "6.0-liter V12",
"horsepower": 600,
"acceleration": "0 to 100 km/h in 3.7 seconds",
"top_speed": "over 320 km/h"
},
"features": {
"aerodynamics": "advanced",
"stability_technologies": "cutting-edge",
"stability_control": "exceptional during high-speed maneuvers"
},
"pricing": {
"original_price": "$1.5 million",
"production_run": 5,
"rarity": "highly sought after by racing enthusiasts and collectors"
}
}
# as you can see, you can mix and match different data types such as strings, int/floats, bools, dicts, lists, etc
jsonstring = json.dumps(mercedes_clr_gtr)
print(jsonstring)
{"name": "Mercedes CLR GTR", "performance": {"engine": "6.0-liter V12", "horsepower": 600, "acceleration": "0 to 100 km/h in 3.7 seconds", "top_speed": "over 320 km/h"}, "features": {"aerodynamics": "advanced", "stability_technologies": "cutting-edge", "stability_control": "exceptional during high-speed maneuvers"}, "pricing": {"original_price": "$1.5 million", "production_run": 5, "rarity": "highly sought after by racing enthusiasts and collectors"}}
Popcorn Hack!
Make your own example using dict
with a car (you can search up its specs)
Formatting
import json
porsche_911 = {
"name": "Porsche 911",
"performance": {
"engine": "3.0-liter twin-turbo flat-six",
"horsepower": 379,
"acceleration": "0 to 100 km/h in 4.2 seconds",
"top_speed": "291 km/h"
},
"features": {
"driving_assistance": "adaptive cruise control",
"exterior": "iconic design",
"interior": "premium materials"
},
"pricing": {
"original_price": "$101,200",
"production_run": "ongoing",
"rarity": "exclusive"
}
}
# Example 1: Default formatting
json_string_1 = json.dumps(porsche_911)
print("Example 1:\n", json_string_1)
# Example 2: Pretty-printing with 2 spaces indentation
json_string_2 = json.dumps(porsche_911, indent=2)
print("\nExample 2:\n", json_string_2)
# Example 3: Pretty-printing with no spaces between keys and values
json_string_3 = json.dumps(porsche_911, indent=4, separators=(',', ': '))
print("\nExample 3:\n", json_string_3)
Example 1:
{"name": "Porsche 911", "performance": {"engine": "3.0-liter twin-turbo flat-six", "horsepower": 379, "acceleration": "0 to 100 km/h in 4.2 seconds", "top_speed": "291 km/h"}, "features": {"driving_assistance": "adaptive cruise control", "exterior": "iconic design", "interior": "premium materials"}, "pricing": {"original_price": "$101,200", "production_run": "ongoing", "rarity": "exclusive"}}
Example 2:
{
"name": "Porsche 911",
"performance": {
"engine": "3.0-liter twin-turbo flat-six",
"horsepower": 379,
"acceleration": "0 to 100 km/h in 4.2 seconds",
"top_speed": "291 km/h"
},
"features": {
"driving_assistance": "adaptive cruise control",
"exterior": "iconic design",
"interior": "premium materials"
},
"pricing": {
"original_price": "$101,200",
"production_run": "ongoing",
"rarity": "exclusive"
}
}
Example 3:
{
"name": "Porsche 911",
"performance": {
"engine": "3.0-liter twin-turbo flat-six",
"horsepower": 379,
"acceleration": "0 to 100 km/h in 4.2 seconds",
"top_speed": "291 km/h"
},
"features": {
"driving_assistance": "adaptive cruise control",
"exterior": "iconic design",
"interior": "premium materials"
},
"pricing": {
"original_price": "$101,200",
"production_run": "ongoing",
"rarity": "exclusive"
}
}
JSON to Python
import json
x = '{ "name":"John", "age":30, "city":"New York"}' # mr morts example json (im too lazy to come up with something original the mercedes clr gtr took waay to much time)
y = json.loads(x) # js equivalent is JSON.parse()
print(y) # returns a dict
print(y["age"])
{'name': 'John', 'age': 30, 'city': 'New York'}
30
Assignment!
Create code that does the following
- Uses a dictionary
- Contains at least 3 different types of variables in the dict, one of which must be a list
- Changes keys in the dict, including a key in the list
- Converts the dict to JSON
Extra Credit: do some kind of math in your code to change a key
Ideas: some recipe thing.
Here’s Nolan’s example:
import json # make sure to skibidi import
possesions = {
"owner": "Lil Bro",
"dollars": 50,
"food": [
"apps",
"pizza",
"banana"
]
}
print(possesions)
# bob the minion eats part of the banana
possesions["food"][2] = "half-eaten banana"
print(possesions["food"])
# fanum tax
possesions["dollars"] = possesions["dollars"] / 2
print(possesions["dollars"]) # notice that it changes to a float
# json
print(json.dumps(possesions))
{'owner': 'Lil Bro', 'dollars': 50, 'food': ['apps', 'pizza', 'banana']}
['apps', 'pizza', 'half-eaten banana']
25.0
{"owner": "Lil Bro", "dollars": 25.0, "food": ["apps", "pizza", "half-eaten banana"]}