Python to JSON conversion
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 Set To JSON
import json
# Python set
fruits = {"apple", "banana", "cherry"}
# Convert set to JSON by first converting it to a list
json_fruits = json.dumps(list(fruits))
print(json_fruits) # Output: ["banana", "apple", "cherry"] (order may vary)
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)
Hack #3
- Try to create a mix of list and dictionaries to represent a real world collection of data
- The system i created is a Library System
# List of dictionaries representing books in a library
library = [
{
"title": "The Six of Crow",
"author": "Leigh Bardugo",
"genre": "Fantasy",
"copies_available": 2,
"borrowers": [
{"name": "Katherine Chen", "borrow_date": "2024-09-10"},
{"name": "Aditi Bandaru", "borrow_date": "2024-09-15"}
]
},
{
"title": "A Game of Thrones",
"author": "George R.R. Martin",
"genre": "Action",
"copies_available": 1,
"borrowers": [
{"name": "Soni Dhenuva", "borrow_date": "2024-09-08"}
]
},
{
"title": "Percy Jackson : The Last Olympian",
"author": "Rick Riordan",
"genre": "Adventure",
"copies_available": 0,
"borrowers": [
{"name": "Sanya Kapoor", "borrow_date": "2024-09-05"},
]
}
]
# Display information about each book in the library
for book in library:
print(f"Title: {book['title']}")
print(f"Author: {book['author']}")
print(f"Genre: {book['genre']}")
print(f"Copies Available: {book['copies_available']}")
print("Borrowers:")
for borrower in book['borrowers']:
print(f" - {borrower['name']} (Borrowed on: {borrower['borrow_date']})")
print("\n")