JSON
JSON (JavaScript Object Notation) is a text-based, language-independent data-interchange format. It consists of two structural collections: * Key-value pairs (m...
Definition
JSON (JavaScript Object Notation) is a text-based, language-independent data-interchange format. It consists of two structural collections:
- Key-value pairs (maps, dictionaries).
- Ordered lists of values (arrays, lists).
Why It Exists
Web services need a standard, lightweight format to exchange structured data. JSON is readable, supported out-of-the-box by almost all programming languages, and parses directly into native objects, making it the industry standard for API integration.
How It Works
PARSING AND DESERIALIZATION
[Raw HTTP Text Payload] ──► json.loads() ──► [Python Dictionary]
"{\"temp\": 0.7}" {"temp": 0.7}
1. **UTF-8 Transmission**: JSON is transmitted over the network as a raw UTF-8 encoded string.
2. **Grammar Checks**: The parser verifies the string format (keys must be enclosed in double quotes, strings must be escaped, trailing commas are disallowed).
3. **Object Instantiation**: The string is parsed into corresponding nested Python data structures.Real-World Example
Every time you call the OpenAI API, the parameters (prompt, temperature, model choice) are sent to the server as a serialized JSON string. The server processes the request and returns a JSON response containing the generated text:
{
"choices": [
{
"message": {
"role": "assistant",
"content": "Hello!"
}
}
]
}Python Example
Here is a data validation wrapper that parses and validates a JSON string, raising a structured exception if it contains invalid types or keys:
import json
from typing import Dict, Any
class JSONValidator:
"""Validates raw text payloads against schema key types."""
def __init__(self, schema: Dict[str, type]):
self.schema = schema
def validate_string(self, raw_json: str) -> Dict[str, Any]:
try:
data = json.loads(raw_json)
except json.JSONDecodeError as e:
raise ValueError(f"Corrupt JSON payload: {e}")
# Check keys and types
for key, expected_type in self.schema.items():
if key not in data:
raise KeyError(f"Missing required parameter key: '{key}'")
if not isinstance(data[key], expected_type):
raise TypeError(f"Key '{key}' must be of type {expected_type.__name__}.")
return data
if __name__ == "__main__":
schema_definition = {"model": str, "temperature": float, "tokens": int}
validator = JSONValidator(schema_definition)
# Valid payload
payload = '{"model": "gpt-4", "temperature": 0.7, "tokens": 100}'
print("Validated:", validator.validate_string(payload))Interview Questions
- Beginner: What are the data types supported by JSON?
- Intermediate: Why are keys in a JSON string always enclosed in double quotes instead of single quotes?
- Advanced: How would you handle a JSON payload that contains dynamic keys and nested objects of varying depths when writing a schema validator?
Interview Answers
- Beginner: JSON supports Strings, Numbers, Boolean (
true/false), Null (null), Objects (dictionaries), and Arrays (lists). - Intermediate: The JSON specification requires double quotes for keys and string values to ensure language compatibility, as many programming languages do not treat single quotes as valid string delimiters.
- Advanced: I would write a recursive validation function. The validator checks if a value is a dictionary. If it is, the function recursively validates its child keys and values against a schema definition mapping, allowing it to validate nested JSON structures of any depth.
Common Mistakes
- Trailing commas: Placing a comma after the final item in a JSON object or array. Python allows trailing commas in list definitions, but the JSON specification does not, and parsers will throw a
JSONDecodeError.
Assignment
Write a Python script that takes a complex dictionary structure (containing lists, strings, and floats) and writes it to a file as a formatted JSON string, verifying the output is valid.