JSON Data Types

Introduction

JSON, or JavaScript Object Notation, is a lightweight data format used by modern APIs to exchange information between clients and servers. Every value inside a JSON document belongs to a data type. A name is usually a string, an age is usually a number, an active status is usually a boolean, an address is usually an object, skills are usually an array, and a missing middle name may be represented as null. These distinctions look simple, but they matter deeply in API design and API testing.

APIs do not only care that a field exists. They also care what kind of value the field contains. If an API expects age as a number and the request sends "age": "30", the JSON syntax is valid, but the data type is wrong. If an API expects active as a boolean and the request sends "active": "true", the value looks understandable to a human, but it is still a string. If an API expects an array of employees and receives one object, the structure is wrong even though the payload may be valid JSON.

For API testers, JSON data type validation is one of the most important parts of request and response testing. Correct data types prevent parsing errors, protect data integrity, make client applications reliable, and ensure the API follows its contract. Wrong data types can cause validation failures, database issues, incorrect calculations, UI defects, schema mismatches, automation failures, and inconsistent behavior between environments.

This tutorial explains JSON data types from a practical API testing perspective. It covers strings, numbers, booleans, objects, arrays, null values, complete JSON examples, JSON data types versus Java data types, request validation, response validation, schema validation, REST Assured examples, Postman examples, Karate examples, real-world examples, common data type mistakes, best practices, and interview-ready explanations.

What Are JSON Data Types?

JSON data types define the kinds of values that can be stored inside a JSON document. JSON supports six built-in data types: string, number, boolean, object, array, and null. Every JSON value must belong to one of these types. The data type tells parsers and applications how to interpret the value.

A string represents text. A number represents numeric values. A boolean represents true or false. An object represents a collection of key-value pairs. An array represents an ordered collection of values. Null represents the absence of a value. These six types are enough to model simple and complex API data structures.

In simple terms, JSON data types specify the type of value associated with each key in a JSON document. A field such as "name": "John" uses a string value. A field such as "age": 30 uses a number value. A field such as "active": true uses a boolean value. The API contract should define which type each field expects.

JSON Data Types Overview

The six JSON data types are easy to list, but they need to be understood with testing discipline. A string is written in double quotes, such as "John". A number is written without quotes, such as 25 or 99.95. A boolean is written as lowercase true or false. An object is written using curly braces, such as { "city": "Chicago" }. An array is written using square brackets, such as ["Java", "SQL"]. Null is written as lowercase null.

These types can be combined inside one JSON document. A user object can contain a string name, numeric age, boolean active status, nested address object, skills array, and null manager value. This flexibility is why JSON is useful for real APIs.

For testers, the main question is not only whether the response is valid JSON. The main question is whether each field uses the type promised by the API specification. If a client application expects a number and receives a string, it may fail or produce incorrect output. Type correctness is therefore a contract issue, not just a formatting preference.

String Data Type

A string represents textual data. Strings must be enclosed in double quotes. They can contain letters, numbers, spaces, symbols, and other characters supported by JSON encoding. Strings are used for names, cities, countries, email addresses, usernames, status values, messages, descriptions, identifiers, dates, timestamps, and codes.

{
  "name": "John"
}

More string examples include:

{
  "city": "Chicago",
  "country": "USA",
  "status": "ACTIVE"
}

The string "Software Testing" is valid because it uses double quotes. The value 'Software Testing' is invalid JSON because JSON does not allow single quotes for strings. This is a common mistake when testers move between JavaScript-style examples and strict JSON payloads.

String validation should go beyond checking that a field is a string. Testers may need to validate minimum length, maximum length, allowed characters, email format, date format, enum values, empty strings, leading spaces, trailing spaces, special characters, and case sensitivity. A field can be the correct type and still be invalid for business rules.

Number Data Type

Numbers represent numeric values. JSON supports integers, decimal numbers, negative numbers, and scientific notation. Unlike many programming languages, JSON does not distinguish between integer, long, float, double, or decimal as separate JSON types. They are all represented as the JSON number type.

{
  "age": 30,
  "salary": 75000.50
}

A negative number is also valid:

{
  "temperature": -5
}

Scientific notation is valid JSON number syntax:

{
  "distance": 1.5e3
}

Numbers should not be quoted when they are intended to be numeric values. "age": "30" sends a string, not a number. Some APIs may convert it, but strict APIs should reject it if the schema expects a number. For testing, it is important to verify whether the API enforces numeric types correctly.

Number validation should include boundary values, zero, negative numbers, decimals, precision, rounding, maximum values, minimum values, invalid strings, null values, and business limits. Financial APIs should pay special attention to decimals and precision. Pagination APIs should validate page size, page number, offset, and limit as numeric values.

Boolean Data Type

A boolean represents one of two logical values: true or false. In JSON, boolean values are lowercase and unquoted. The values true and false are valid. The values TRUE, FALSE, "true", and "false" are not boolean values in JSON.

{
  "active": true
}

Another example is:

{
  "verified": false
}

Boolean fields are common in APIs. Examples include active, enabled, verified, deleted, primary, default, locked, subscribed, available, taxable, visible, and completed. Each of these fields carries business meaning. A user with "active": false may not be allowed to log in. A product with "available": false may not be shown for sale.

Boolean testing should cover true, false, quoted values, uppercase values, numeric alternatives such as 1 and 0 if unsupported, missing values, null values, and invalid strings. Testers should verify that the API does not loosely treat any non-empty string as true because that can create serious logic defects.

Object Data Type

A JSON object is a collection of key-value pairs enclosed within curly braces. Objects are used to group related information together. They represent entities such as users, employees, products, orders, addresses, payments, profiles, and errors.

{
  "address": {
    "city": "Chicago",
    "zip": "60007"
  }
}

In this example, address is an object value. It contains its own fields: city and zip. Objects allow APIs to represent structured data naturally. Instead of placing every address field at the top level, related address details are grouped together.

Object validation includes checking whether the object exists, whether required child fields exist, whether optional fields behave correctly, whether nested values have correct types, whether null is allowed, and whether extra fields are returned or rejected. A response can be valid JSON but still wrong if an expected object is returned as a string, array, or null.

Array Data Type

A JSON array is an ordered collection of values enclosed within square brackets. Arrays may contain strings, numbers, booleans, objects, arrays, or null values. They are commonly used for lists of records or lists of simple values.

{
  "skills": [
    "Java",
    "Selenium",
    "REST Assured"
  ]
}

The skills field is an array of strings. An API can also return arrays of objects, such as employees, products, orders, transactions, or comments. Arrays preserve order, which matters when validating sorted responses or ranked results.

Although JSON allows arrays to contain mixed data types, most APIs use arrays containing similar types for consistency. A skills array should usually contain strings. An employees array should usually contain employee objects. A list of IDs should use one consistent ID type. Mixed arrays make clients harder to write and tests harder to maintain.

Array validation includes checking existence, size, empty array behavior, item data types, object structure, duplicates, order, sorting, pagination, filtering, nested arrays, and schema compliance. A response can have the correct array field but still be defective if some items have inconsistent structure.

Null Data Type

Null indicates that no value has been assigned. It is written as lowercase null without quotes. Null is a real JSON value, and it is different from an empty string, an empty object, an empty array, or a missing field.

{
  "middleName": null
}

An empty string looks like this:

{
  "middleName": ""
}

These two examples are not the same. An empty string means the field exists and contains a string with no characters. Null means no value is assigned. A missing field means the field is not present at all. APIs should define how each case is handled.

Null testing is important for required fields, optional fields, update requests, partial updates, database mappings, and client display behavior. A null value may be valid for optional middle name, but invalid for email. A null address object may be invalid if the user must have an address. A null array may be inconsistent if the contract says empty collections should be returned as [].

Complete JSON Example

A complete JSON object can combine all six supported data types:

{
  "id": 101,
  "name": "John",
  "age": 30,
  "active": true,
  "salary": 75000.50,
  "address": {
    "city": "Chicago",
    "country": "USA"
  },
  "skills": [
    "Java",
    "Selenium"
  ],
  "manager": null
}

In this example, id, age, and salary are numbers. name is a string. active is a boolean. address is an object. skills is an array. manager is null.

This is the kind of response testers often validate in real API testing. It is not enough to verify that the response body exists. The test should confirm important fields, values, and types. If the API contract says id is numeric, then returning "101" as a string may be a defect. If skills should be an array, returning a comma-separated string such as "Java,Selenium" is structurally wrong.

JSON Data Type vs Java Data Type

JSON data types are simpler than Java data types. JSON has one number type, while Java has int, long, float, double, BigDecimal, and wrapper classes. JSON has object, while Java may map that object to a class, map, record, or DTO. JSON has array, while Java may map it to an array, list, set, or collection.

A JSON string maps naturally to a Java String. A JSON boolean maps to boolean or Boolean. A JSON null maps to null. A JSON object may map to a Java class or Map. A JSON array may map to a Java List or array.

Testers using REST Assured should remember that numeric values may be represented differently depending on the parser and value size. A small whole number may be read as Integer, a larger number as Long, and decimal values as Float, Double, or BigDecimal depending on configuration. This matters when writing type assertions. The core API expectation should be clear, and the framework assertion should be written accordingly.

Data Type Validation in API Testing

Data type validation checks whether each field in a request or response uses the expected JSON type. QA engineers should verify correct data type, required fields, optional fields, null handling, empty strings, arrays, objects, and schema validation. This validation should be part of both positive and negative API testing.

For example, if the response is:

{
  "age": 30
}

The tester should verify that age exists and that age is a number. If the response is:

{
  "active": true
}

The tester should verify that active is a boolean. Similar checks apply to strings, objects, arrays, and null values.

Data type validation protects API consumers. A frontend application may format numeric values, calculate totals, show boolean switches, loop through arrays, or access object fields. If the API returns wrong types, the client code may break even when the visible value appears correct.

Request Payload Data Type Validation

Request validation confirms that the API accepts correct data types and rejects incorrect data types. If a create product endpoint expects price as a number, a valid payload may contain "price": 500. A negative test can send "price": "500" and verify the documented error behavior. This confirms that the API enforces its contract.

Request data type testing should include strings sent where numbers are expected, numbers sent where strings are expected, strings sent where booleans are expected, null sent where objects are required, objects sent where arrays are required, arrays sent where objects are required, and missing fields. The API should return clear validation errors for invalid payloads.

Testers should avoid assuming that automatic conversion is acceptable. Loose conversion can hide client defects. For example, if the backend accepts "active": "false" and converts any non-empty string to true, the system may behave incorrectly. Strong APIs validate types explicitly.

Response Payload Data Type Validation

Response validation confirms that the API returns fields with the expected data types. If the contract says balance is a number, the response should not return "balance": "2500.75". If the contract says verified is boolean, the response should not return "verified": "true". If the contract says employees is an array, the response should not return a single employee object under the same field.

Response data type issues are serious because API consumers depend on predictable structure. A mobile app may crash if it expects an array and receives null. A report may sort incorrectly if numeric values are returned as strings. A UI may display boolean values incorrectly if they are returned as text.

Schema validation is often the best way to catch response data type issues across many fields. Targeted assertions should still be used for important business fields. Together, schema validation and field assertions provide strong coverage.

Data Type Validation for Collections

Collection validation is important because many APIs return arrays of objects rather than a single object. A response may contain an array of users, products, orders, transactions, or validation errors. In that case, checking only the array field is not enough. The tester should also validate the data types inside each item.

For example, an employees array may contain employee objects where id is a number, name is a string, active is a boolean, and skills is an array. If the first employee has correct types but the fifth employee has id as a string, the response is inconsistent. This can happen when data comes from multiple systems or when optional transformation logic is applied incorrectly.

Collection type validation should also cover empty arrays. An empty array may be valid, but the response should still follow the expected structure. If the API normally returns "employees": [] for no results, it should not return "employees": null in one environment and an empty array in another. Consistency makes client applications easier to build and test.

Data Type Validation for Error Responses

Error responses also need data type validation. Teams often focus on successful responses and forget that clients depend on error response structure as well. A validation error may include fields such as status, errorCode, message, timestamp, path, and details. Each field should have a defined type.

For example, status may be a number, errorCode may be a string, message may be a string, and details may be an array of objects. If details sometimes appears as a string and sometimes as an array, client error handling becomes harder. If status is returned as "400" instead of 400, it may break strict clients or contract tests.

Negative API tests should therefore verify both the status code and the error payload data types. This is especially important for public APIs, microservices, and applications where frontend teams rely on consistent error contracts to display useful messages.

Data Type Rules and API Contracts

Data type expectations should be part of the API contract. Documentation should clearly state whether each field is a string, number, boolean, object, array, or null. It should also define whether a field is required, optional, nullable, read-only, write-only, or conditionally present. Without these rules, testers and consumers are forced to guess.

OpenAPI specifications and JSON Schema files are commonly used to document these rules. They make the expected structure machine-readable, which means tests can automatically validate responses against the contract. This reduces ambiguity and catches changes that may otherwise reach consumers unnoticed.

When the actual API behavior differs from the contract, testers should report the mismatch clearly. The issue may be in the code, the contract, or both. The important point is that the API should not leave clients uncertain about how to interpret values. Stable data type contracts are a foundation of reliable integration.

Common Data Type Mistakes

One common mistake is sending a string instead of a number:

{
  "age": "30"
}

If the API expects a number, the value should be:

{
  "age": 30
}

Another mistake is sending a string instead of a boolean:

{
  "active": "true"
}

The correct boolean value is:

{
  "active": true
}

A third mistake is sending null where an object is required:

{
  "address": null
}

If address is required, the payload should contain an address object:

{
  "address": {
    "city": "Chicago"
  }
}

Another common mistake is returning an object instead of an array:

{
  "employees": {
    "id": 1
  }
}

If multiple employees are expected, the response should use an array:

{
  "employees": [
    {
      "id": 1
    }
  ]
}

JSON Schema Validation

JSON Schema helps verify data types, required fields, value ranges, string length, array size, object structure, enums, formats, and nested rules. It is commonly used in automated API testing because it can validate the response contract consistently.

A schema can define that name must be a string, age must be a number, active must be a boolean, address must be an object, skills must be an array, and manager may be null. If the API returns a wrong type, schema validation fails immediately.

Schema validation is useful for broad structural coverage, but it should not replace business assertions. A schema can confirm that status is a string, but a business assertion confirms that the value is DELIVERED after an order is delivered. Both types of validation are useful.

REST Assured Example

REST Assured can validate response fields using Hamcrest matchers. For example:

given()
.when()
  .get("/users/101")
.then()
  .statusCode(200)
  .body("age", instanceOf(Integer.class));

This verifies that the parsed age value is represented as an Integer. Depending on the parser and value, numeric values may be represented as Integer, Long, Float, Double, BigDecimal, or another numeric type. Tests should account for the framework behavior.

For more robust contract validation, REST Assured can validate against a JSON schema. Field-level assertions can then verify business values such as name, status, balance, or active flag. This combination avoids relying on only one type of check.

Postman Example

Postman can validate data types in the Tests tab using JavaScript assertions. For example:

pm.test("Age is a number", function () {
  pm.expect(pm.response.json().age).to.be.a("number");
});

A boolean check may look like this:

pm.test("Active is boolean", function () {
  pm.expect(pm.response.json().active).to.be.a("boolean");
});

Postman is useful for quickly checking response values and types while exploring an API. For repeatable checks, these assertions should be saved in collections and run through Newman in CI. When many fields need type validation, schema-based validation may be cleaner than many individual assertions.

Karate Example

Karate provides concise built-in markers for data type validation:

Then match response.age == '#number'
And match response.name == '#string'
And match response.active == '#boolean'

Karate can also validate arrays, objects, nullable fields, and repeated structures. This makes it useful for API tests where the expected JSON shape should be readable in the test itself.

For example, if a response contains an array of employees, Karate can verify each item follows an expected structure. This is helpful when validating collection endpoints because every item should follow the same contract.

Real-World Examples

An employee API may return a string name and numeric age:

{
  "name": "John",
  "age": 30
}

A product API may return numeric price:

{
  "price": 500
}

A banking API may return a decimal balance:

{
  "balance": 2500.75
}

A customer API may return a boolean verification status:

{
  "verified": true
}

Each example is simple, but each one has a type expectation. If these values are returned as strings, the response may still be readable to humans, but it may violate the API contract. Automated tests should catch that difference.

Best Practices

Use the correct data type for every field. Follow the API schema. Keep arrays consistent in element type whenever possible. Use null only when supported by the API. Avoid sending numbers as strings unless the API explicitly expects them. Validate data types in both requests and responses. Use schema validation for automated tests.

Keep data type rules documented. API consumers should know whether IDs are strings or numbers, whether date values are strings in ISO format, whether money values are numbers or strings, whether empty collections return arrays, and whether optional fields are omitted or returned as null.

Use controlled test data for strict validation. If a test needs to confirm numeric values, boolean flags, and arrays, the expected data should be predictable. For shared environments, avoid brittle assertions that depend on unstable records. Validate type rules consistently even when values change.

Common Mistakes

Sending numbers as strings is one of the most common mistakes:

{
  "price": "500"
}

The correct numeric representation is:

{
  "price": 500
}

Using uppercase boolean values is another mistake. TRUE is invalid JSON, while true is valid. Confusing null and empty string is also common. "name": "" means a blank string exists, while "name": null means no value is assigned.

Mixing data types in arrays is another issue. An array such as ["John", 25, true] is valid JSON, but it is usually poor API design unless explicitly required. Arrays should normally contain consistent element types so clients and tests can process them safely.

A final mistake is testing only visible values and ignoring types. A UI may display 500 whether the API returns a number or a string, but the difference matters for sorting, calculations, validation, and client code. API tests should verify the actual JSON type.

Interview Questions

A common interview question is: how many data types does JSON support? JSON supports six data types: string, number, boolean, object, array, and null. A strong answer should also briefly explain each type and give examples.

Another question is: does JSON distinguish between integers and floating-point numbers? The answer is no. JSON represents both as the number data type. However, programming languages and parsers may map JSON numbers to different numeric types internally.

Interviewers may ask the difference between null and an empty string. Null means no value. An empty string means a string value exists but contains no characters. They may also ask why data type validation is important in API testing. The answer is that it ensures requests and responses conform to the API specification, prevents parsing errors, protects client applications, and maintains data integrity.

Interview-Ready Explanation

JSON data types define the kinds of values that can be stored in a JSON document. JSON supports six built-in data types: string, number, boolean, object, array, and null. Strings are enclosed in double quotes. Numbers represent numeric values and are written without quotes. Booleans are lowercase true or false. Objects contain key-value pairs. Arrays hold ordered collections of values. Null represents the absence of a value.

In API testing, validating JSON data types is essential because APIs expect request and response payloads to follow the contract. If a number is sent as a string, a boolean is sent as text, an object is replaced with null, or an array is replaced with an object, the API behavior can become incorrect. Clients may fail while parsing, calculations may be wrong, filters and sorting may behave incorrectly, and schema validation may fail.

Testers validate data types using field assertions, JSONPath, schema validation, REST Assured, Postman, Karate, and other API testing tools. Good validation checks both request payloads and response payloads. It confirms that fields exist, required fields are present, optional fields behave correctly, null is handled properly, arrays and objects follow expected structure, and each value uses the correct JSON type.

Key Takeaway

JSON data types are the foundation of reliable API payloads. They determine how every value in a request or response should be interpreted. A value that looks correct to a human can still be wrong if its JSON type does not match the API contract. The difference between 30 and "30", true and "true", null and "null", or an array and object is not cosmetic. It affects real application behavior.

For API testers, the practical rule is to validate type as well as value. Confirm that strings, numbers, booleans, objects, arrays, and null values are used correctly. Use schema validation for broad contract coverage and targeted assertions for business-critical fields. Strong data type validation helps prevent parsing errors, contract defects, client failures, inaccurate calculations, and inconsistent API behavior.