Welcome to Part 2 of our JSON tutorial series. In Part 1: Introduction to JSON, we introduced the basics of JSON, including its syntax and data types. Now, we’ll delve into best practices and conventions that help ensure your JSON is readable, maintainable, and interoperable. Adhering to conventions is crucial when working in teams or building APIs that others will consume.
Why Conventions Matter
Consistent use of conventions in your JSON documents offers several benefits:
- Readability: Well-formatted and consistently named JSON is easier for humans to read and understand.
- Maintainability: Clear conventions make it easier to modify and extend JSON structures over time.
- Interoperability: While JSON itself is standardized, consistent practices in areas like key naming can reduce friction when integrating different systems or libraries.
- Reduced Errors: Clear structure and naming can help prevent misunderstandings and bugs.
Topics covered in this article:
- Naming Conventions for Keys
- Escape Characters
- Formatting JSON for Readability
- Structuring JSON Data Effectively
- JSON Style Guides
- Common Pitfalls and How to Avoid Them
Naming Conventions for Keys
Choosing a consistent naming convention for your JSON keys (property names) is one of the most visible aspects of your JSON style. While JSON itself doesn’t enforce a specific case style for keys, consistency within a project or API is highly recommended.
Common Cases
- camelCase: The first word is lowercase, and subsequent words start with an uppercase letter (e.g., firstName, orderDetail, isActive). This is very common in JavaScript and thus frequently seen in JSON.
- snake_case: All words are lowercase and separated by underscores (e.g., first_name, order_detail, is_active). This style is prevalent in languages like Python and Ruby.
- kebab-case: All words are lowercase and separated by hyphens (e.g., first-name, order-detail, is-active). While common in HTML attributes and some URL paths, it’s less common for JSON keys directly because hyphens can require special handling (e.g., bracket notation) in some programming languages when accessing properties.
- PascalCase (or UpperCamelCase): Similar to camelCase, but the first word also starts with an uppercase letter (e.g., FirstName, OrderDetail, IsActive). This is often used for type names or class names in object-oriented programming.
The most important aspect is to pick one convention and stick to it throughout your JSON documents or API. camelCase is arguably the most prevalent in the JSON world, largely due to JSON’s JavaScript origins, for example, recommends camelCase for member names.
Plural vs. Singular for Array Keys
It’s a common convention to use plural nouns for keys whose values are arrays of items. For example, use “users” for an array of user names, or “values” for an array of number. This makes the intent clear.
{
"users": ["Fred", "James"],
"values": [5,533,86]
}
Avoiding Ambiguity and Special Characters
- Use descriptive key names that clearly indicate the data they represent.
- Avoid using spaces or special characters (other than those used by your chosen convention, like underscores or hyphens if you opt for snake_case/kebab-case) in key names. While technically possible to have keys with spaces (e.g., “first name”), they require bracket notation for access in many languages (e.g., data[“first name”]) and can be less convenient.
- Avoid using keywords from the target language consuming the JSON data i.e. ‘class’ or ‘namespace’, ‘int’ etc. Also identifiers that would be invalid in the target language, i.e. a property names that do not start with a letter.
The choice of naming convention can significantly impact the developer experience when consuming an API. Clear, consistent, and predictable names reduce cognitive load and make the API easier to work with. When an API mixes naming conventions or uses obscure abbreviations, developers spend more time deciphering the data structure rather than focusing on their application logic.
Escape Characters
Why is Escaping Necessary?
JSON strings are delimited by double quotes (“). If a string itself contains a double quote, or other characters that have special meaning in JSON, the parser would incorrectly interpret them, leading to syntax errors or data corruption. Escaping involves placing a backslash (\) before these special characters, signaling to the parser that the following character should be treated as a literal part of the string, not as a structural element of the JSON.
Characters That Must Be Escaped
The JSON specification (RFC 8259) defines specific characters that must be escaped within a JSON string:
- Double Quote (“): Escaped as \”
- Example: “He said, \”Hello!\””
- Backslash (\): Escaped as \\ (since the backslash itself is the escape character)
- Example: “C:\\Program Files\\MyApp”
- Forward Slash (/): Escaped as \/
- While technically optional in most contexts, it’s often escaped to avoid issues when embedding JSON within HTML <script> tags (where </script> could prematurely close the tag) or for consistency.
- Control Characters: These non-printable characters are represented by escape sequences:
- Backspace (\b): Escaped as \b
- Form Feed (\f): Escaped as \f
- Newline (\n): Escaped as \n
- Carriage Return (\r): Escaped as \r
- Tab (\t): Escaped as \t
- Unicode Characters: Any Unicode character can be escaped using the \uXXXX notation, where XXXX is the four-digit hexadecimal code point of the character. This is particularly useful for characters that are not easily represented directly in the basic JSON string (e.g., emojis, characters from non-Latin scripts).
- Example: “Emoji: \uD83D\uDE00” (a smiling emoji)
How Escaping Works
When a JSON parser encounters a backslash followed by one of the defined escape characters, it interprets the sequence as a single literal character rather than its special meaning. For example, \” is understood as a literal double quote within the string, not as the end of the string.
Formatting JSON for Readability
Raw JSON data, especially if minified (all on one line with no extra whitespace), can be very difficult for humans to read. “Prettifying” or formatting JSON with consistent indentation and line breaks dramatically improves its readability.
Indentation
- Use spaces for indentation. The most common are 2 or 4 spaces per level. Tabs can also be used, but spaces are often preferred for consistency across different editors and environments.
- Each level of nesting (objects within objects, arrays within objects, etc.) should be indented further.
Line Breaks
- Place each key/value pair on a new line for objects.
- Place each element on a new line for arrays, especially if the array contains objects or longer values.
- Opening braces { and brackets [ often appear on the same line as the key or at the end of a line, with the content indented on subsequent lines, and the closing brace } or bracket ] on its own new line, aligned with the opening.
Whitespace Around Colons and Commas
- Typically, include one space after the colon (:) separating a key and its value.
- Include one space after the comma (,) separating key/value pairs or array elements.
Ordering of Keys
While JSON objects are officially unordered collections of key/value pairs, some developers or tools prefer to order keys for consistency, either alphabetically or by logical grouping. This is not a requirement of the JSON specification but can aid readability in some contexts.
Example: Poorly Formatted vs. Well-Formatted JSON
Poorly Formatted (Minified):
{"name":"Jane Doe","age":32,"isStudent":false,"courses":[{"title":"History 101","credits":3},{"title":"Math 202","credits":4}]}
Well-Formatted (2-space indentation):
{
"name": "Jane Doe",
"age": 32,
"isStudent": false,
"courses": [
{
"title": "History 101",
"credits": 3
},
{
"title": "Math 202",
"credits": 4
}
]
}
Readability is not merely a cosmetic concern. Well-formatted JSON is significantly easier to debug, as the structure is clear, and errors like mismatched braces or missing commas become more apparent. For teams working collaboratively, a consistent formatting style reduces merge conflicts and makes code reviews more efficient. Many IDEs and text editors, including specialized tools like Liquid Studio – JSON Editor, have built-in functions or plugins to automatically format JSON, ensuring consistency and saving development time.
Structuring JSON Data Effectively
How you structure your JSON can impact its usability, performance, and maintainability.
Nesting: When and How Much?
JSON allows for deeply nested objects and arrays, which is powerful for representing hierarchical data.
- Benefits of Nesting: Can group related data logically, making the JSON self-contained and potentially reducing the need for multiple requests if fetching related data (denormalization).
- Drawbacks of Excessive Nesting: Can make JSON harder to navigate and parse. Very deep nesting might indicate a complex data model that could be simplified or that related data might be better fetched separately.
- Balance is key. Consider how the data will be consumed and updated.
Using Arrays for Collections
When you have a list of items, use a JSON array. This is the natural way to represent collections.
Representing Dates and Times
JSON doesn’t have a native date/time type. The most common and recommended practice is to store dates and times as strings in the ISO 8601 format e.g., “2023-11-15T14:35:00Z” for UTC, or “2023-11-15T09:35:00-05:00” for a specific offset). This format is unambiguous and widely supported by date parsing libraries.
Avoid using localized date formats i.e. “10/2/2024” as this could be read as the 10th of Feb or 2nd of Oct depending on if the server is in the US or anywhere else in the world.
Handling Null vs. Omitting Fields
As well as the other data types number, string, boolean, object and array you can also have a null value.
{
"age":null
}
- Use null to explicitly indicate that a key has no value or that the value is intentionally absent.
- Omitting a field entirely can mean the property is not applicable or its value is unknown.
- The choice depends on the semantics of your data and API. Be consistent. If a field is optional and not present, consumers should be prepared for it to be missing, rather than assuming it will always be there with a null value (unless your API contract specifies this).
- It is more typical to omit a property than to set it to null, but in some data structures it makes sense to use null.
The flexibility of JSON, especially when used with schemaless NoSQL databases, means developers have a lot of freedom in how they structure their data. However, this freedom can lead to problems if not managed thoughtfully. Applying principles from database normalization (like ensuring data depends on the whole key and only the key) can be beneficial even in the JSON world to avoid redundancy and update anomalies, though strict adherence isn’t always necessary or desirable for JSON documents that benefit from some denormalization. The goal is to create structures that are both usable and maintainable in the long run. Tools like Liquid Studio can help visualize and manage these structures, making it easier to apply these principles.
JSON Style Guides
A JSON style guide is a document that outlines specific conventions and rules for writing JSON within a particular project, team, or organization. It’s well worth taking the time to write/find a style guide early on in the project.
Benefits of using a style guide:
- Consistency: Ensures everyone writes JSON in the same way.
- Reduced Ambiguity: Clarifies choices for naming, formatting, and structure.
- Improved Collaboration: Makes it easier for team members to understand and work with each other’s JSON.
- Onboarding: Helps new team members get up to speed quickly on JSON practices.
Creating a Simple Style Guide
A style guide might specify:
- Chosen key naming convention (e.g., camelCase).
- Indentation rules (e.g., 2 spaces).
- Guidelines for representing common data types like dates (e.g., ISO 8601).
- Rules for using null vs. omitting fields.
- Preferred structure for common entities.
Common Pitfalls and How to Avoid Them
- String Quoting: All strings in JSON, including keys and string values, must be enclosed in double quotes (“). Single quotes (‘) are not valid.
- Correct: {“name”: “John Doe”}
- Incorrect: {‘name’: ‘John Doe’}
- Trailing Commas: Trailing commas after the last element in an array or the last key/value pair in an object are not allowed in standard JSON. Some parsers might be lenient, but it’s best to avoid them for maximum compatibility.
- Correct: {“name”: “Alice”, “age”: 28}
- Incorrect: {“name”: “Bob”, “age”: 32,}
- Incorrect Data Types: JSON only supports strings, numbers, booleans, arrays, objects, and null. JavaScript concepts like undefined, NaN, Infinity, functions, or Date objects are not valid JSON types directly.
- Correct: {“age”: 25, “isStudent”: true, “scores”: [95,68] }
- Incorrect (using undefined): {“name”: undefined, “marks”: 95}
Comments: The standard for JSON does not support comments. If you need to annotate your JSON, it must be done outside the JSON data itself or by adding descriptive fields (like a “comment” key) within the JSON structure, though this adds to the data payload. Some parsers might be lenient, but it’s best to avoid them for maximum compatibility. Many JSON editors, such as those provided by Liquid Studio, will highlight these syntax errors, helping you catch these issues early.
Summary & What’s Next
In this part, we’ve covered essential best practices and conventions for writing high-quality JSON. By consistently applying naming conventions, formatting your JSON for readability, structuring your data thoughtfully, and being aware of common pitfalls, you can create JSON that is easier to work with, maintain, and share. For tools that assist in applying these best practices, such as formatters and validators, consider exploring Liquid Studio.
In Part 3: Advanced Data Structures in JSON, we will explore how to model more complex data relationships using nested objects, arrays of objects, and combinations thereof.
Navigate This Series:
- Part 1: Introduction to JSON
- Part 2: JSON Best Practices and Conventions (this post)
- Part 3: Advanced Data Structures in JSON
- Part 4: Querying and Transforming JSON Data


3 responses to “JSON Best Practices and Conventions – Part 2 of 4”
[…] Part 2: JSON Best Practices and Conventions […]
[…] 3 of our JSON tutorial series. In the previous parts, we covered the basic syntax in part 1 and best practices and conventions in part 2. Now, we’ll explore how JSON’s simple building blocks—objects and arrays—can be […]
[…] learned about JSON’s basics (Part 1: Understanding JSON), best practices and conventions (Part 2: Best Practices & Conventions) and advanced data structures(Part 3: Advanced Data Structures in JSON), we now turn our attention […]