JSON - JavaScript Object Notation

JSON is a lightweight data interchange format that is easy for people and machines to understand. It is widely used for data exchange between a client and a server, as well as for storing and transporting data. In Python, the `json` module provides methods to convert Python objects into JSON and vice versa. This process is known as serialization (converting Python objects to JSON) and deserialization (converting JSON to Python objects). JSON is used when data is sent from a web server to a webpage.

# using json.dumps method to serialize Python objects into a JSON-formatted string
import json

# Python dictionary
python_dict = {
    "name": "Alice",
    "age": 25,
    "is_student": False,
    "courses": ["Math", "Science"],
    "details": {
        "height": 1.65,
        "address": "123 Main St"
    }
}

# Convert dictionary to JSON string
json_string = json.dumps(python_dict)
print(json_string)

# writes the JSON string representation of python_dict directly into a file
with open('data.json', 'w') as json_file:
    json.dump(python_dict, json_file)


{"name": "Alice", "age": 25, "is_student": false, "courses": ["Math", "Science"], "details": {"height": 1.65, "address": "123 Main St"}}

Formatting

Key Parameters for Formatting JSON:
- `indent`: Adds indentation to each level of the JSON object, making it easier to read
- `separators`: Controls how items are separated in the JSON string. By default, the separators are `(", ", ": ")
- `sort_keys`: When `True`, this sorts the keys in the output JSON by alphabetical order.

import json

python_dict = {
    "name": "Alice",
    "age": 25,
    "is_student": False,
    "courses": ["Math", "Science"],
    "details": {
        "height": 1.65,
        "address": "123 Main St"
    }
}

y = json.dumps(python_dict, indent=4) # `indent` formats the JSON string for readability
print(y + "\n") # '\n' adds a space 

y = json.dumps(python_dict, indent=4, separators=(".", " = ")) # uses a '=' instead of ':'
print(y + "\n")


{
    "name": "Alice",
    "age": 25,
    "is_student": false,
    "courses": [
        "Math",
        "Science"
    ],
    "details": {
        "height": 1.65,
        "address": "123 Main St"
    }
}

{
    "name" = "Alice".
    "age" = 25.
    "is_student" = false.
    "courses" = [
        "Math".
        "Science"
    ].
    "details" = {
        "height" = 1.65.
        "address" = "123 Main St"
    }
}

JSON in JavaScript

JSON (JavaScript Object Notation) is natively supported in JavaScript and is widely used for data interchange. You can convert JavaScript objects to JSON strings using the built-in `JSON` object.


// Step 1: Creating a JavaScript object
const person = {
    name: "Alice",
    age: 30,
    isStudent: false,
    courses: ["Math", "Science"]
};

// Step 2: Converting the object to a JSON string
const jsonString = JSON.stringify(person);
console.log("JSON String:", jsonString);

// Step 3: Parsing the JSON string back into a JavaScript object
const parsedPerson = JSON.parse(jsonString);
console.log("Parsed Person Object:", parsedPerson);

// Accessing properties from the parsed object
console.log("Name:", parsedPerson.name);  // Output: Alice
console.log("Age:", parsedPerson.age);    // Output: 30

Popcorn Hack: Use JSON to make a dictionary, modify it, and update the changes

import json

book_data = {
    "title": "Python for Beginners",
    "author": "Jane Smith",
    "publication_year": 2022,
    "genres": [
        "Education",
        "Programming",
        "Technology"
    ],
    "ratings": {
        "average_rating": 4.7,
        "number_of_ratings": 180
    }
}

book_json = json.dumps(book_data, indent=4)
print(book_json)

book_data['ratings']['average_rating'] = 4.9

updated_book_json = json.dumps(book_data, indent=4)
print(updated_book_json)

Homework

1. Create a dictionary with at least 3 keys. Print the dictionary.
2. Start with this dictionary: person = {"name": "Alice", "age": 30}
i. Update the age to 31
ii. print the updated dictionary.

Grading for Hacks and Homework

  • all requirements must be completed
  • be creative! go above and beyond when possible
  • show understanding by explaining each step