Catalog / JSON Formatting Cheatsheet
JSON Formatting Cheatsheet
A comprehensive guide to JSON formatting, covering syntax, data types, best practices, and tools for creating readable and maintainable JSON documents.
JSON Basics & Syntax
Core Concepts
JSON (JavaScript Object Notation): A lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate.
|
Data Types: JSON supports several primitive data types:
|
Syntax Rules
Key-Value Pairs |
Keys must be strings enclosed in double quotes. Values can be any of the supported JSON data types. Example: |
Objects |
A collection of key-value pairs, enclosed in curly braces Example: |
Arrays |
An ordered list of values, enclosed in square brackets Example: |
Nesting |
JSON objects and arrays can be nested to represent complex data structures. Example:
|
Formatting Best Practices
Indentation
Use consistent indentation to improve readability. A common practice is to use 2 or 4 spaces for each level of indentation. Avoid using tabs as they can be interpreted differently by different editors. |
Example (2 spaces):
Example (4 spaces):
|
Line Breaks
Insert line breaks after each comma to separate key-value pairs in objects and elements in arrays. This makes the structure easier to follow. |
Example:
|
Consistent Quotes
Always use double quotes for strings. JSON specification requires keys to be enclosed in double quotes as well. |
Valid: Invalid: |
Avoiding Trailing Commas
Do not include trailing commas after the last key-value pair in an object or the last element in an array. Trailing commas are invalid JSON and can cause parsing errors. |
Invalid:
Valid:
|
Advanced Formatting & Tools
JSON Validators
Use JSON validators to ensure your JSON documents are well-formed and valid. Validators can catch syntax errors, incorrect data types, and other issues. |
Online Validators:
Command-line Tools:
|
JSON Formatters/Beautifiers
Use formatters to automatically indent and add line breaks to your JSON documents, making them more readable. |
Online Formatters:
Text Editor Plugins:
|
Schema Validation
Use JSON Schema to define the structure and data types of your JSON documents. This helps ensure data consistency and can be used to validate JSON documents programmatically. |
Key Concepts:
Example:
|
Common Issues & Solutions
Encoding Issues
Ensure your JSON documents are encoded in UTF-8 to support a wide range of characters. Incorrect encoding can lead to parsing errors or data corruption. |
Solution:
|
Escaping Special Characters
Special characters in strings, such as double quotes, backslashes, and control characters, must be escaped using backslashes. |
Common Escape Sequences:
|
Large Numbers
JavaScript’s |
Example:
|