Fall 2024 - P1
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.2 Python Conversion to JSON
Why is it necessary to convert Python code into JSON?
Cross-Platform Compatibility
- JSON (JavaScript Object Notation) is a lightweight, text-based data format that is widely used across different platforms and programming languages. By converting Python data structures (such as dictionaries and lists) into JSON, you can easily share data between Python applications and systems written in other languages like JavaScript, Java, C++, or even mobile apps.
Data Transfer
- JSON is compact and human-readable, making it suitable for transferring data over the internet (e.g., through RESTful APIs). By converting Python data into JSON, you ensure that the data can be transmitted efficiently between servers, applications, or browsers.
Converting Python list to JSON
import json
# Python list
data = ["apple", "banana", "cherry"]
# Convert list to JSON
json_data = json.dumps(data)
print(json_data) # Output: ["apple", "banana", "cherry"]
Converting Python Dictionary To JSON
import json # you will need to import this library
# python dictionary
x = {
"name": "Soni",
"age": 15,
"city": "San Diego"
}
# convert into JSON
# we first CALL the library and use the dumps() function
# to call the library and use dumps(), we do json.dumps()
# note: do you know of function machines in math? where you put in the variable, it does some operations, and outputs it?
# a code function is the same! it takes some data, does some code on it, and outputs it!
# essentially, we say "Hey! JSON library! I would like to use your dumps() function!"
# and then we give the function what we want to dump: "Here is the thing I want to dump into JSON!"
# then the library says back "Here you go! Here's your JSON! I stored it in the y variable!"
y = json.dumps(x)
print(y) # the result is a JSON string
Converting Python Tuple To JSON
import json
# Python tuple
coordinates = (10, 20)
# Convert tuple to JSON
json_coordinates = json.dumps(coordinates)
print(json_coordinates) # Output: [10, 20]
Converting Python Boolean, None, and other types To JSON
import json
# Python data with booleans and None
data = {
"isActive": True,
"count": None
}
# Convert to JSON
json_data = json.dumps(data)
print(json_data) # Output: {"isActive": true, "count": null}
Formating The Code
# the result above isn't easy to read. let's fix that by formatting!
import json
x = {
"name": "John",
"age": 30,
"city": "New York"
}
print("Indent")
y = json.dumps(x, indent=4) # we call the function but say "Please indent it for me!"
print(y + "\n") # the "\n" is a newline seperator and adds a space between each print statement
print("Indent + seperator")
y = json.dumps(x, indent=4, separators=(".", " = ")) # we change the seperator
print(y + "\n")
print("Indent + seperator + sorted")
y = json.dumps(x, indent=4, separators=(".", " = "), sort_keys=True) # now we are sorting them
print(y)