Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool
Creating Curriculum Materials Around JSON Formatters
JSON (JavaScript Object Notation) has become the de facto standard for data interchange on the web and beyond. While its structure is simple, reading large or complex JSON data that lacks proper indentation and spacing can be challenging. This is where JSON formatters (or beautifiers) come in.
Building a JSON formatter is a fantastic project for developers learning fundamental programming concepts, string manipulation, data structures, and recursion. This page outlines how to structure curriculum materials around this engaging topic, suitable for various skill levels.
What is a JSON Formatter?
A JSON formatter takes a raw, unformatted JSON string and outputs a new string with consistent indentation and line breaks, making the data structure clear and readable.
Consider this unformatted JSON:
[{"id":1,"name":"Alice","courses":["Math","Science"]},{"id":2,"name":"Bob","courses":["History"]}]
A formatter transforms it into something like this (using 2-space indentation):
[
{
"id": 1,
"name": "Alice",
"courses": [
"Math",
"Science"
]
},
{
"id": 2,
"name": "Bob",
"courses": [
"History"
]
}
]
The goal is to visually represent the nested structure of objects (`{ ... }`) and arrays (`[ ... ]`).
Why Teach JSON Formatting?
Teaching students to build a JSON formatter offers several educational benefits:
- Reinforces JSON Structure: Students must deeply understand the rules for objects, arrays, strings, numbers, booleans, and null, and how they nest.
- String Manipulation: It involves iterating through a string, identifying specific characters (like `{`, `}`, `[`, `]`, `:`, `,`), and building a new string.
- Algorithm Design: Students need to devise a logic to handle indentation levels as they enter and exit nested structures.
- Recursion/Stack Usage: Handling nested JSON naturally lends itself to recursive approaches or using a stack to keep track of the current indentation level and context (object or array).
- Error Handling: Students can explore basic error detection, though a full JSON validator is a separate, more complex task.
- Practical Utility: It's a useful tool they can use or expand upon.
Key Concepts to Cover
- JSON Syntax Rules: Review the valid data types and structure (key-value pairs in objects, ordered elements in arrays).
- Indentation: The core concept. How many spaces or tabs to use per level? How to increase/decrease the indentation?
- Whitespace: Understanding that whitespace is generally ignored in JSON *except* within strings. The formatter adds meaningful whitespace.
- Handling Delimiters: Specifically processing `{`, `}`, `[`, `]`, `:`, `,`. These characters dictate where new lines and indentation changes occur.
- Handling Data Types: How to output strings (including escaping), numbers, booleans, and null without adding extra unwanted whitespace inside them.
- Nesting: The crucial part. When you see `{` or `[`, increase indentation. When you see `}` or `]`, decrease indentation *before* adding the character.
- Commas and Colons: Adding new lines *after* commas within objects/arrays and spaces *after* colons in objects.
Curriculum Structure & Examples
Phase 1: Basic Indentation (Flat Structures)
Start simple. Ignore nesting initially. Teach how to add indentation for key-value pairs or array elements in a flat structure. Focus on identifying commas and deciding where to add newlines and the current indentation string.
Conceptual JavaScript/TypeScript (Simplified):
function basicFormat(jsonString: string, indent = ' '): string {
let result = '';
let currentIndent = '';
let inString = false; // Simple state to avoid formatting inside strings
for (let i = 0; i < jsonString.length; i++) {
const char = jsonString[i];
if (char === '"') {
inString = !inString;
}
if (!inString) {
if (char === ',' || char === ':' || char === '[' || char === '{' || char === ']' || char === '}') {
result += char;
// Add newline and indent after certain characters (basic logic)
if (char === ',' || char === '[' || char === '{') {
result += '\n' + currentIndent;
}
// Add space after colon
if (char === ':') {
result += ' ';
}
continue; // Move to next character
}
// Add indentation logic here based on nesting level (to be added later)
}
result += char; // Add character if not a special delimiter or inside string
}
// This basic example needs refinement for nesting
return result;
}
Note: This is a highly simplified conceptual example. A real formatter needs more sophisticated state and parsing logic.
Phase 2: Handling Nesting (Recursion/Stack)
Introduce the concept of indentation level. Each time you encounter an opening brace `{` or bracket `[`, increment the level. Each time you encounter a closing brace `}` or bracket `]`, decrement the level. The current indentation string is the `indent` character repeated `level` times.
This is a great opportunity to teach recursion. A function could process a "value", and if that value is an object or array, it recursively calls formatting logic for the nested structure, passing down the increased indentation level. Alternatively, demonstrate using a stack to manage indentation levels iteratively.
Conceptual Indentation Logic:
let indentLevel = 0;
const indentSize = 2; // Use 2 spaces
const indentChar = ' ';
// When encountering '{' or '[':
indentLevel++;
// Add '\n' + indentChar.repeat(indentLevel)
// When encountering '}' or ']':
indentLevel--;
// Add '\n' + indentChar.repeat(indentLevel) + the character
// When encountering ',':
// Add ',' + '\n' + indentChar.repeat(indentLevel)
// When encountering ':':
// Add ':' + ' ' // Add space after colon
Phase 3: Edge Cases & Options
- Empty Objects/Arrays: Ensure `{}` and `[]` are handled correctly without extra newlines.
- Strings with Special Characters: While formatting doesn't change string *content*, students should be aware of escaped characters (`\\n`, `\\"`, etc.) and that the formatter shouldn't break them.
- Indentation Type: Allow choosing between spaces and tabs, and specifying the number of spaces.
- Compact Formatting: An optional challenge: output the JSON with minimal whitespace on a single line.
- Basic Validation: Add checks for common syntax errors (unmatched braces/brackets, trailing commas - though not strictly JSON, some parsers allow).
Suggested Project Structure
Structure the curriculum as a project where students incrementally build their formatter:
- Start with a function that takes a string and returns a string.
- Implement logic for flat objects (newlines after commas, space after colon).
- Implement logic for flat arrays (newlines after commas).
- Combine flat object and array handling.
- Introduce indentation level tracking.
- Implement recursive handling of nested objects and arrays.
- Add options for indent size and character (space/tab).
- Handle empty objects/arrays correctly.
- (Optional) Add basic syntax error detection.
Provide plenty of test cases, from simple flat structures to deeply nested ones with various data types.
Conclusion
Creating a JSON formatter is a practical and deeply educational programming exercise. It provides concrete examples of string processing, algorithmic thinking, and handling hierarchical data. By structuring curriculum materials to progress from basic formatting to handling complex nesting and options, instructors can guide developers of all levels to build a useful tool while solidifying core programming concepts.
Need help with your JSON?
Try our JSON Formatter tool to automatically identify and fix syntax errors in your JSON. JSON Formatter tool