JSON Syntax Rules

Introduction

JSON, which stands for JavaScript Object Notation, is the most widely used data format for modern API communication. When a web application, mobile application, microservice, or automation script sends data to an API, the request body is often written in JSON. When the server sends data back, the response body is also commonly written in JSON. It is popular because it is compact, readable, language independent, and easy to parse in Java, JavaScript, Python, C#, and almost every other programming language used in software development.

However, JSON is not just plain text written in a convenient style. It has strict syntax rules. A missing comma, a single quote, an unquoted key, an extra closing brace, a trailing comma, or an invalid boolean value can make the entire document invalid. When JSON is invalid, the server may reject the request with a bad request response, the API framework may fail before business logic is reached, or the client may fail while parsing the response. Many API issues that appear to be functional defects are actually syntax problems in the JSON payload.

For API testers, JSON syntax rules are essential knowledge. A tester who understands JSON syntax can quickly identify whether a failure is caused by invalid data format, incorrect data type, schema mismatch, payload construction error, or actual application behavior. This skill is useful in Postman, REST Assured, Karate, browser developer tools, mock servers, contract testing, automation frameworks, and CI pipelines. It also helps testers communicate clearly with developers when a request payload or response body is malformed.

This tutorial explains JSON syntax rules in a practical API testing context. It covers JSON objects, arrays, keys, values, double quotes, colons, commas, trailing commas, supported data types, strings, numbers, booleans, null values, nested objects, arrays of objects, case sensitivity, duplicate keys, valid and invalid examples, syntax validation tools, REST Assured usage, Postman usage, Karate usage, common syntax errors, best practices, mistakes to avoid, and interview-ready explanations.

What Are JSON Syntax Rules?

JSON syntax rules define the structure and formatting required for a JSON document to be valid. A JSON document can be simple or complex, but it must follow the same basic grammar. Objects must be written with curly braces. Arrays must be written with square brackets. Keys must be enclosed in double quotes. String values must also be enclosed in double quotes. A colon must separate each key from its value. Commas must separate multiple key-value pairs or multiple array items. Supported data types must be used correctly.

In simple terms, JSON syntax rules decide whether a JSON document can be parsed. If the syntax is valid, a JSON parser can convert the text into a structured object that software can use. If the syntax is invalid, parsing fails. This is why API tools often show errors such as unexpected token, invalid JSON, expected comma, expected property name, or end of input while parsing JSON.

Syntax correctness is different from business correctness. A JSON request can be syntactically valid but still rejected by the API because required fields are missing or values do not satisfy business rules. For example, { "age": "30" } is valid JSON, but it may be invalid for an API that expects age to be a number instead of a string. Testers should understand both syntax validation and schema or business validation.

Basic JSON Structure

Every JSON document starts with either an object or an array. An object starts with an opening curly brace and ends with a closing curly brace. An array starts with an opening square bracket and ends with a closing square bracket. These two structures are the foundation of JSON.

{
}

The empty object above is valid JSON. It contains no fields, but the structure is correct. An empty array is also valid JSON:

[
]

Most API requests and responses use objects at the top level because objects can describe named data fields. For example, a user payload may contain name, email, role, and active status. Some APIs return arrays at the top level when the response represents a list of records, although many APIs wrap arrays inside an object with metadata such as total count, page number, and page size.

JSON Must Start with an Object or Array

A valid JSON document cannot begin directly with a loose key-value pair. The key-value pair must belong to an object. This is one of the first rules beginners often miss because they may write only the field they want to test.

{
  "name": "John"
}

The example above is valid because the key-value pair is inside curly braces. An array of objects is also valid:

[
  {
    "name": "John"
  }
]

The following example is invalid because it starts directly with a key-value pair:

"name": "John"

In API testing, this mistake can happen when a tester copies part of a payload into Postman or automation code without including the enclosing braces. The server will not receive a valid JSON document, so the request may fail before field-level validation occurs.

Objects Use Curly Braces

A JSON object groups related key-value pairs. It is written using curly braces. Each key describes a property, and each value provides the data for that property. Objects are used to represent structured entities such as users, orders, products, addresses, payments, and configuration details.

{
  "city": "Chicago",
  "state": "Illinois"
}

The object above contains two fields. Both keys are strings, both values are strings, and the fields are separated by a comma. An object can contain strings, numbers, booleans, arrays, nested objects, or null values. The object itself may also be nested inside another object or array.

Using square brackets for object-like data is incorrect. Square brackets represent an array, not a named object structure. If a request body is expected to be an object and the tester sends an array, the JSON syntax may still be valid, but the API contract is violated. This is an important difference: syntax may be correct while payload shape is wrong.

Arrays Use Square Brackets

A JSON array stores multiple values in a sequence. It is written using square brackets. Array values may be strings, numbers, booleans, objects, arrays, or null values. In API responses, arrays commonly represent lists such as users, products, orders, transactions, messages, or validation errors.

{
  "skills": [
    "Java",
    "Selenium",
    "API Testing"
  ]
}

The skills field contains an array of strings. Each array item is separated by a comma. The order of items in an array is meaningful because arrays are ordered collections. This matters when testing sorted API responses, ordered steps, ranked results, or timeline data.

Arrays can also contain objects. This is very common in API responses that return multiple records:

{
  "employees": [
    {
      "id": 1,
      "name": "John"
    },
    {
      "id": 2,
      "name": "Alice"
    }
  ]
}

When validating arrays, testers should check not only syntax but also item count, item structure, mandatory fields, data types, order, empty array behavior, and how arrays behave with filters and pagination.

Keys Must Be in Double Quotes

Every JSON object key must be enclosed in double quotes. This rule is stricter than JavaScript object literal syntax. In JavaScript, an object may allow unquoted property names in some situations, but JSON does not. JSON keys are always strings, and strings must use double quotes.

{
  "name": "John"
}

The following example is invalid JSON because the key is not quoted:

{
  name: "John"
}

This is a frequent mistake when people manually type request bodies. Some editors or browser consoles may tolerate JavaScript-style objects, but API request bodies using application/json must be valid JSON. Postman, JSONLint, IDE validators, and REST Assured parsers can catch this problem quickly.

Strings Must Use Double Quotes

String values in JSON must also use double quotes. Single quotes are not valid JSON string delimiters. If a value is text, it must be surrounded by double quotes.

{
  "city": "Chicago"
}

The next examples are invalid. The first value is not quoted, and the second uses single quotes:

{
  "city": Chicago
}
{
  "city": 'Chicago'
}

Unquoted text may be interpreted as an unknown token, and single quotes will usually cause parsing failure. This rule is especially important when test data is built dynamically in automation. If a string value is inserted into a JSON body without quotes, the final payload becomes invalid.

Key-Value Pairs Use a Colon

A JSON object stores data as key-value pairs. A colon separates each key from its value. The key appears on the left, the value appears on the right, and the colon tells the parser that the value belongs to that key.

{
  "age": 30
}

Using an equal sign is invalid JSON:

{
  "age" = 30
}

This mistake is common for people who are used to assigning variables in programming languages. JSON is a data format, not a programming statement. It uses colons for key-value structure and commas for separation.

Commas Separate Multiple Values

When an object has multiple key-value pairs, commas must separate them. When an array has multiple items, commas must also separate those items. Without commas, the parser cannot determine where one field or item ends and the next begins.

{
  "name": "John",
  "city": "Chicago"
}

The following example is invalid because the comma between the two fields is missing:

{
  "name": "John"
  "city": "Chicago"
}

Missing commas are among the most common JSON syntax errors. They often happen when a new field is added to an existing payload. A tester should learn to scan JSON carefully around recently added fields because the error may be located near the previous line, not always at the exact line reported by the parser.

No Trailing Comma

JSON does not allow a trailing comma after the last object field or the last array item. This rule surprises many beginners because some programming languages and JavaScript environments allow trailing commas. Strict JSON does not.

{
  "name": "John",
  "city": "Chicago"
}

The next example is invalid because there is a comma after the final field:

{
  "name": "John",
  "city": "Chicago",
}

Trailing commas commonly appear when testers comment, remove, or reorder fields during experimentation. Since JSON itself does not support comments either, testers should be careful when editing payloads manually. A clean formatter or validator helps prevent this class of error.

Supported JSON Data Types

JSON supports six primary data types: string, number, boolean, object, array, and null. Every value in JSON must belong to one of these types. Understanding these types is critical because API schemas usually define expected types for each field.

{
  "name": "John",
  "age": 30,
  "active": true,
  "address": {
    "city": "Chicago"
  },
  "skills": ["Java", "API Testing"],
  "manager": null
}

In this example, name is a string, age is a number, active is a boolean, address is an object, skills is an array, and manager is null. The syntax is valid, and the payload also communicates data types clearly.

API testers should separate syntax validation from type validation. A string value in quotes is valid syntax, but it may be the wrong type for a field. A number without quotes is valid syntax, but it may violate business rules if negative numbers are not allowed. Schema validation is used to verify expected data types beyond basic syntax.

Numbers Do Not Use Quotes

Numbers in JSON are written without quotes. They may be integers or decimals, and they may be positive or negative. When a number is enclosed in quotes, it becomes a string, not a number.

{
  "age": 30,
  "price": 499.99
}

The following payload is syntactically valid JSON, but age is a string:

{
  "age": "30"
}

Whether this is acceptable depends on the API contract. Some APIs may convert strings to numbers internally, but relying on conversion is risky. A strict API should reject wrong data types when the schema expects a number. Testers should verify how the API behaves when numeric fields are sent as strings, blank values, decimals where integers are expected, negative values, or extremely large numbers.

Boolean Values Are Unquoted

JSON boolean values are true and false. They are lowercase and they are not enclosed in quotes. A quoted boolean is a string, not a boolean.

{
  "active": true,
  "verified": false
}

The following payload is syntactically valid JSON, but the value is a string:

{
  "active": "true"
}

The following payload is invalid because JSON booleans must be lowercase:

{
  "active": TRUE
}

Boolean fields are common in APIs: active status, deleted flag, email verified flag, enabled flag, subscribed flag, primary address flag, and permission flags. Testers should verify correct boolean handling and should not assume that "true", 1, yes, or Y are accepted unless the API contract explicitly allows them.

Null Uses the Keyword null

JSON represents an intentionally empty or missing value with the keyword null. It must be lowercase and unquoted. A quoted "null" is a string containing the letters n-u-l-l, which is completely different from an actual null value.

{
  "middleName": null
}

The next example is valid JSON syntax but usually wrong when a null value is intended:

{
  "middleName": "null"
}

Null handling is important in API testing because APIs often treat missing fields, null fields, and empty strings differently. For example, an update request may ignore a missing field, clear a field when null is sent, and save a blank value when an empty string is sent. Testers should understand these differences before writing assertions.

Objects Can Be Nested

JSON objects can contain other objects. Nesting allows a payload to represent structured data in a natural way. A customer may have an address object, a payment may have billing details, an order may have shipping information, and a user may have profile settings.

{
  "employee": {
    "name": "John",
    "city": "Chicago"
  }
}

Nested objects must follow the same syntax rules as top-level objects. Their keys need double quotes, their fields need commas, and their braces must be balanced. Deep nesting can make payloads harder to read, so formatting becomes important. Pretty-printed JSON helps testers see structure clearly.

When testing nested objects, validate both syntax and meaning. The parent object may be present, but a nested mandatory field may be missing. A nested value may be the wrong data type. The structure may be syntactically valid but not match the schema expected by the API.

Arrays Can Contain Objects

Arrays of objects are extremely common in JSON API responses. A response may return a list of employees, orders, products, comments, transactions, or validation errors. Each item in the array is usually an object with its own fields.

{
  "employees": [
    {
      "id": 1,
      "name": "John"
    },
    {
      "id": 2,
      "name": "Alice"
    }
  ]
}

Each object inside the array must be separated by a comma. The array itself must be enclosed in square brackets, and each object must be enclosed in curly braces. This combination of brackets and braces is easy to break when manually editing payloads.

For testers, arrays of objects require careful validation. If the response is filtered, every object should satisfy the filter. If the response is sorted, objects should appear in the expected order. If the response is paginated, array size and metadata should match the requested page and size.

JSON Is Case-Sensitive

JSON keys and string values are case-sensitive. The keys Name and name are different keys. The values ACTIVE, Active, and active may also be treated differently depending on the API rules.

{
  "Name": "John",
  "name": "Alice"
}

The payload above contains two separate keys. While it is syntactically valid, it is confusing and should generally be avoided. API contracts should define consistent naming conventions, such as camelCase for JSON keys.

Case sensitivity affects testing in multiple ways. A request with "userName" may work while "username" is ignored or rejected. A status value of "ACTIVE" may be accepted while "active" fails. Testers should verify both documented valid casing and invalid casing behavior.

Duplicate Keys Should Be Avoided

Duplicate keys occur when the same key appears more than once in the same object. Some parsers accept this, but behavior can differ. Many parsers keep the last value, some keep the first value, and some reject the payload. Because behavior is not reliable across systems, duplicate keys should be avoided.

{
  "name": "John",
  "name": "Alice"
}

This payload is problematic because it is unclear which value should represent the name. Even if a tool parses it, the result may not match what the tester expected. Duplicate keys can hide data issues and create inconsistent behavior between Postman, automation frameworks, backend services, and logs.

API testers should include duplicate key checks when validating robustness, especially for important fields. The expected behavior should be documented. A strict API may reject duplicate keys. A lenient parser may accept them, but teams should understand the risk.

Valid JSON Example

A practical valid JSON payload combines several data types while following all syntax rules. The following example represents an employee record with nested address details, an array of skills, a boolean status, and a null manager value.

{
  "id": 101,
  "name": "John",
  "age": 30,
  "active": true,
  "address": {
    "city": "Chicago",
    "zip": "60007"
  },
  "skills": [
    "Java",
    "Selenium",
    "API Testing"
  ],
  "manager": null
}

This payload is valid because the document starts with an object, all keys use double quotes, string values use double quotes, numbers are unquoted, booleans are lowercase and unquoted, null is lowercase and unquoted, nested objects use braces, arrays use brackets, fields are separated by commas, and there is no trailing comma.

In an API test, this payload may be used as a request body for creating or updating an employee. Syntax validation confirms that the payload can be parsed. Schema validation confirms that fields have expected types. Business validation confirms whether values are allowed.

Invalid JSON Examples

Invalid JSON examples help testers recognize common mistakes quickly. A missing quote around a key is invalid:

{
  name: "John"
}

A missing comma between fields is invalid:

{
  "name": "John"
  "city": "Chicago"
}

A trailing comma after the last field is invalid:

{
  "name": "John",
}

A missing closing brace is invalid:

{
  "name": "John"

Single quotes are invalid:

{
  'name': 'John'
}

Uppercase boolean values are invalid:

{
  "active": TRUE
}

These errors are simple, but they are common in real testing work. When an API returns a parsing error, testers should first verify whether the request body is valid JSON before investigating deeper business logic.

JSON Syntax Validation in API Testing

JSON syntax validation checks whether the JSON document is structurally valid. Testers should verify correct braces, correct brackets, quoted keys, quoted string values, proper colons, proper commas, no trailing commas, correct nesting, valid arrays, valid booleans, valid null values, and no accidental duplicate keys.

Syntax validation is usually the first level of validation. If syntax fails, deeper checks cannot be trusted because the payload cannot be parsed correctly. In request testing, invalid JSON may produce a 400 Bad Request response. In response testing, invalid JSON may cause the automation framework to fail while extracting fields.

JSON syntax validation should be included in both manual and automated API workflows. Manually, testers can use Postman, JSON validators, browser tools, or IDE support. In automation, frameworks such as REST Assured, Jackson, Gson, Karate, and JSON schema validators can detect malformed JSON while parsing or validating response bodies.

JSON Validators and Tools

Several tools help identify JSON syntax issues before a request is sent or while debugging a response. JSONLint and similar validators can validate and format JSON. Postman highlights many syntax problems when the body type is set to raw JSON. Browser developer tools can display JSON responses and reveal parsing issues. IDEs such as IntelliJ IDEA, Eclipse, and VS Code provide JSON formatting and validation support.

In Java automation, Jackson and Gson are commonly used to serialize and deserialize JSON. REST Assured can parse JSON responses and extract fields with JSONPath. Karate has built-in JSON handling. These tools reduce manual string manipulation and lower the chance of creating invalid payloads.

Testers should avoid building large JSON request bodies by concatenating strings wherever possible. Object mapping, template files, request builders, and serialization libraries are safer and easier to maintain. If a test dynamically changes JSON, the final payload should still be logged or validated in a readable format for debugging.

REST Assured Example

REST Assured can send a JSON request body as a string. The string must contain valid JSON:

String body = """
{
  "name": "John",
  "city": "Chicago"
}
""";

given()
  .contentType("application/json")
  .body(body)
.when()
  .post("/users")
.then()
  .statusCode(201);

If the JSON string is invalid, the server may reject the request. If response parsing is attempted on invalid JSON, REST Assured may throw parsing-related errors. A better approach in larger frameworks is to create Java objects and serialize them into JSON. This avoids many syntax mistakes because the library generates valid JSON.

REST Assured tests should also validate returned JSON fields. For example, a test can assert that name equals John, active is true, or skills contains expected values. Syntax validation is the foundation, but field and schema validation complete the test.

Postman Example

In Postman, testers usually select Body, choose raw, and then select JSON as the format. This makes Postman treat the request body as JSON and provide visual hints for syntax issues. A valid body may look like this:

{
  "name": "John",
  "city": "Chicago",
  "active": true
}

Postman is useful for quickly experimenting with payloads. Testers can add fields, remove fields, change data types, and observe how the API responds. The Tests tab can also validate response JSON:

pm.test("Response is valid JSON", function () {
  pm.response.json();
});

If the response body is not valid JSON, the call to pm.response.json() fails. For request bodies, Postman may show formatting warnings, but testers should still pay attention to the actual response because some APIs return detailed parse errors and others return generic messages.

Karate Example

Karate supports readable multiline JSON request bodies. This makes it convenient for API test scenarios:

Given request
"""
{
  "name": "John",
  "city": "Chicago"
}
"""
When method POST
Then status 201

Karate can also treat JSON as structured data instead of plain text. That allows testers to match fields, arrays, objects, and patterns. Because Karate is designed for API testing, it reduces the need for manual parsing code.

Even with helpful tools, testers still need to understand JSON syntax rules. Tooling can show that a payload is invalid, but understanding the rule helps the tester fix it quickly and explain the issue clearly.

Common JSON Syntax Errors

The most common JSON syntax errors include missing quotes around keys, missing quotes around string values, single quotes, missing commas, trailing commas, missing braces, missing brackets, extra braces, invalid boolean capitalization, invalid null capitalization, and duplicate keys. These errors are easy to introduce when editing JSON manually.

Another common issue is confusing valid JSON with valid API data. For example, { "age": "30" } is valid JSON, but it may fail schema validation. Similarly, { "active": "true" } is valid JSON, but it sends a string instead of a boolean. A payload can pass syntax validation and still be wrong for the API.

Encoding issues can also affect JSON. Special characters, newline characters, quotation marks inside strings, and backslashes must be escaped correctly. If a string contains a double quote, the quote must be escaped so it does not prematurely end the string. Testers working with addresses, messages, descriptions, file paths, or copied text should watch for escaping problems.

Best Practices

Always validate JSON before sending important requests. Use a formatter or validator when manually preparing request bodies. Keep JSON pretty-printed during development so structure is easy to inspect. Use double quotes for all keys and string values. Avoid duplicate keys. Use meaningful key names and follow the naming convention defined by the API, such as camelCase.

Use the correct data type for each field. Send numbers as numbers when the API expects numbers, booleans as booleans when the API expects booleans, and null as null when a field should be empty. Do not rely on the server to convert strings into numbers or booleans unless this behavior is explicitly documented.

For automation, prefer object serialization or JSON libraries instead of manual string concatenation. Store reusable request bodies in template files when that matches the framework style. Log final request bodies in debug mode so syntax issues can be investigated. Validate response JSON structure before extracting fields deeply. When schema validation is available, use it to complement syntax validation.

Common Mistakes

A common mistake is using single quotes because they are familiar from JavaScript or other languages. JSON requires double quotes. Another mistake is adding a trailing comma after the last field or array item. This may look harmless, but strict parsers reject it.

Forgetting commas between fields is also common, especially when adding a new field in the middle of a payload. Missing closing braces or brackets happen frequently in nested JSON. Testers should use indentation and bracket matching tools to prevent these issues.

Another mistake is treating strings and numbers as interchangeable. A field value of "30" and a field value of 30 are not the same. The same applies to "true" and true, or "null" and null. These differences affect schema validation, backend processing, database storage, and response behavior.

Finally, testers sometimes assume that a successful HTTP response means the JSON was correct. Some APIs silently ignore unknown fields or convert values loosely. Strong testing should verify that the API accepted the intended data, stored it correctly, and returned the expected structure.

Interview Questions

A common interview question is: what are JSON syntax rules? A strong answer is that JSON syntax rules define how a valid JSON document must be written, including objects with curly braces, arrays with square brackets, keys and string values in double quotes, colons between keys and values, commas between fields or items, supported data types, and no trailing commas.

Another common question is: can JSON use single quotes? The answer is no. JSON requires double quotes for keys and string values. Single quotes may work in JavaScript object literals, but they are not valid JSON.

Interviewers may ask what data types JSON supports. JSON supports string, number, boolean, object, array, and null. They may also ask whether JSON is case-sensitive. The answer is yes. Keys and string values are case-sensitive, and boolean and null literals must be lowercase.

A practical interview question is: why is JSON syntax important in API testing? The answer is that invalid JSON can cause requests to fail before business logic is executed, can break response parsing, can hide real defects, and can produce misleading test failures. Testers need to distinguish JSON syntax issues from API functionality issues.

Interview-Ready Explanation

JSON syntax rules define the structure and formatting required to create a valid JSON document. A JSON document must start with either an object or an array. Objects use curly braces and contain key-value pairs. Arrays use square brackets and contain ordered values. Keys must be written in double quotes, string values must be written in double quotes, a colon separates each key from its value, and commas separate multiple fields or array items.

JSON supports strings, numbers, booleans, objects, arrays, and null values. Numbers, booleans, and null values are not quoted when they are intended to be those data types. Boolean values are lowercase true and false, and null is lowercase null. JSON does not allow trailing commas, does not allow single quotes, and should avoid duplicate keys. JSON is case-sensitive, so name and Name are different keys.

In API testing, understanding JSON syntax is important because request and response bodies often use JSON. A small syntax issue can cause a request to fail with a parsing error, and an invalid response can break automation. Testers should validate JSON syntax, verify expected data types, avoid malformed payloads, use validators or framework support, and separate syntax problems from schema and business validation problems.

Key Takeaway

JSON syntax rules are the foundation of reliable API communication. They define how data must be written so clients, servers, tools, and automation frameworks can parse it correctly. Objects, arrays, double quotes, colons, commas, valid data types, lowercase booleans, lowercase null, balanced braces, and no trailing commas are not optional formatting preferences. They are required rules for valid JSON.

For API testers, the practical rule is simple: validate the format before judging the behavior. If the JSON is malformed, the API may never reach the business logic you intended to test. Once syntax is valid, continue with schema validation, business rule validation, response validation, and negative testing. A tester who understands JSON syntax can debug API failures faster, write better request payloads, create stronger automation, and explain defects with more precision.