What Is JSON? Syntax, Data Types, JavaScript Objects, and JSON Schema
Learn JSON syntax and data types, see valid examples, compare JSON with JavaScript objects, and use JSON Schema to validate real data contracts.
JSON, or JavaScript Object Notation, is a text file format for exchanging structured data between applications. JSON is not a database, nor a programming language, nor a schema. It is the text that you place on the wire or store in a file when one system needs to give data to another system .
You have already seen JSON if you have opened package.json, inspected a REST API response, copied a webhook payload, edited a VS Code settings file, or looked at a browser Network tab. The useful mental model is simple: JSON is a serialized data value. A program turns an object into JSON text before sending it, and another program parses that text back into its own native data structure.
{
"id": "usr_42",
"name": "Ada Lovelace",
"active": true,
"roles": ["admin", "editor"],
"profile": {
"timezone": "Europe/London",
"newsletter": false
}
}
That example is valid JSON because it is one complete value, uses double-quoted keys and strings, uses lowercase true and false, and contains only JSON data types.
JSON in One Minute
| Question | Practical answer |
|---|---|
| What does JSON stand for? | JavaScript Object Notation |
| What is JSON used for? | API responses, request bodies, config files, logs, data exports, and messages between services |
| Is JSON only for JavaScript? | No. Every major language can parse and generate it |
| Is JSON the same as a JavaScript object? | No. JSON is text with stricter syntax; a JavaScript object literal is code |
| How many JSON data types are there? | Six: object, array, string, number, boolean, and null |
| Can a JSON file start with an array? | Yes. A JSON text can be any single JSON value, though objects and arrays are most common |
| Can JSON contain comments? | No. Comments are allowed in JSONC, not strict JSON |
| How do I validate JSON? | Parse it with a JSON parser, or use a strict JSON Validator |
What Is JSON?
JSON is a standardized text syntax for representing structured data. RFC 8259 describes JSON as a lightweight, text-based, language-independent data interchange format. ECMA-404 defines the same core syntax and intentionally leaves application meaning to the systems using it.
That last point matters. JSON tells you how to write the data:
{
"total": 1299,
"currency": "USD"
}
It does not tell you whether 1299 means dollars, cents, points, or inventory units. Your API contract, docs, JSON Schema, OpenAPI spec, or database model gives the data its meaning.
A JSON Document Is One Value
A valid JSON document contains exactly one top-level JSON value. Most real documents use an object:
{
"status": "ok",
"items": []
}
An array is also common:
[
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]
Primitives are valid JSON too:
42
"hello"
null
In practice, API responses usually use an object wrapper, because it allows for metadata, pagination, errors and future fields:
{
"data": [
{ "id": 1, "name": "Alice" }
],
"meta": {
"page": 1,
"hasMore": false
}
}
The Six JSON Data Types
JSON has four primitive and two structured value types. They are often referred to as the six JSON data types.
| Type | Example | Use it for | Watch out for |
|---|---|---|---|
| Object | { "id": 1 } |
Named fields and nested records | Keys must be strings; duplicate keys are risky |
| Array | [1, 2, 3] |
Ordered lists | Items do not have to share a type, but mixed arrays are harder to use |
| String | "Ada" |
Text, IDs, dates, decimal money | Must use double quotes and valid escapes |
| Number | 42, 3.14, 1.5e10 |
Counts, measurements, safe numeric values | No NaN, no Infinity, no hex, no leading zeros |
| Boolean | true, false |
Binary state | Lowercase only |
| Null | null |
Explicitly empty value | Different from a missing key |
Object
An object is a set of name/value pairs wrapped in {}. Names are strings, so they must be double-quoted.
{
"name": "Alice",
"age": 30,
"active": true
}
RFC 8259 says object names should be unique. Many parsers accept duplicate keys anyway, but they do not all behave the same way. Some keep the last value, some keep the first, and some expose all pairs.
Avoid this:
{
"role": "user",
"role": "admin"
}
If a key matters, write it once.
Array
An array is an ordered list wrapped in [].
["apple", "banana", "cherry"]
Arrays can contain objects:
[
{ "sku": "hat-blue", "quantity": 2 },
{ "sku": "mug-white", "quantity": 1 }
]
JSON allows mixed arrays:
["ok", 200, true, null]
That’s true, but it’s often awkward for typed code, CSV exports, analytics programs, and generated TypeScript interfaces. Homogeneous arrays are generally easier to maintain in API design.
String
A string is Unicode text inside double quotes.
"Hello, world!"
Single quotes are not JSON:
'Hello, world!'
Quotes, backslashes, and control characters inside strings must be escaped:
{
"quote": "She said \"hello\".",
"path": "C:\\Users\\Ada\\notes.json",
"lines": "first line\nsecond line"
}
If you see something that looks like a number, but it’s an identifier (e.g. account ID, order ID, ZIP code, phone number, large external ID), treat it as a string. Those values are not for arithmetic, and the string form avoids leading-zero and precision problems, too.
Number
JSON has one number type.
{
"count": 42,
"ratio": 0.875,
"scientific": 1.5e10
}
Numbers are base-10. JSON does not allow hexadecimal numbers, octal numbers, NaN, Infinity, or leading zeros:
{
"hex": 0xff,
"nan": NaN,
"badLeadingZero": 007
}
For JavaScript clients, be careful with integers larger than 9007199254740991 (Number.MAX_SAFE_INTEGER). If an ID can exceed that range, send it as a string:
{
"invoiceId": "9223372036854775807"
}
For money, prefer integer minor units or documented decimal strings:
{
"amountCents": 1299,
"currency": "USD"
}
Boolean
JSON booleans are exactly true and false.
{
"emailVerified": true,
"smsOptIn": false
}
True, False, yes, no, 1, and 0 are not JSON booleans. They may be meaningful in Python, YAML, SQL, forms, or spreadsheets, but strict JSON parsers reject them or treat them as different types.
Null
null means "this field is present, but the value is empty."
{
"middleName": null
}
That is not the same as omitting the key:
{}
In an API contract, decide which one you mean:
| Shape | Meaning |
|---|---|
"middleName": null |
The field exists, and there is no value |
no middleName key |
The field is unknown, not requested, or not applicable |
"middleName": "" |
The value is an empty string |
This distinction matters for PATCH requests, form submissions, generated types, and database updates.
JSON Syntax Rules That Actually Bite
Strict JSON is intentionally small. These are the rules developers hit most often:
| Rule | Invalid | Valid |
|---|---|---|
| Keys must be double-quoted strings | { name: "Alice" } |
{ "name": "Alice" } |
| Strings use double quotes | { "name": 'Alice' } |
{ "name": "Alice" } |
| No trailing commas | { "a": 1, } |
{ "a": 1 } |
| No comments | { "a": 1 // note } |
{ "a": 1 } |
| Lowercase literals only | { "ok": True } |
{ "ok": true } |
No undefined |
{ "x": undefined } |
{ "x": null } |
| One top-level value | {} {} |
[{ }, { }] |
Whitespace between tokens is insignificant. These two documents parse to the same value:
{"name":"Alice","active":true}
{
"name": "Alice",
"active": true
}
Formatting makes JSON readable, but it does not change the data.
What Is a .json File?
A .json file is a plain text file whose contents are one JSON document. It does not need a header, schema declaration, import statement, or closing marker. Save valid JSON text with the .json extension and tools will generally recognize it.
Common examples:
| File | What it usually contains |
|---|---|
package.json |
Node.js package metadata, scripts, and dependencies |
tsconfig.json |
TypeScript compiler options |
manifest.json |
Browser extension or PWA metadata |
appsettings.json |
.NET application configuration |
composer.json |
PHP package metadata |
To open a JSON file, use a text editor, an IDE, a terminal command, or a JSON Viewer. To create one, write a valid JSON value and save it as name.json.
For example, users.json might contain:
[
{ "id": "usr_1", "name": "Alice", "role": "admin" },
{ "id": "usr_2", "name": "Bob", "role": "editor" }
]
When the file is large or deeply nested, a tree viewer is usually easier than scrolling through raw text.
JSON vs JavaScript Object Literal
JSON looks like JavaScript, but it is not the same thing.
This is a JavaScript object literal:
const user = {
id: 42,
name: "Alice",
active: true,
lastSeen: undefined,
greet() {
return `Hello ${this.name}`;
},
};
This is JSON:
{
"id": 42,
"name": "Alice",
"active": true
}
JSON cannot contain functions, methods, comments, trailing commas, undefined, symbols, Date objects, Map, Set, or computed keys. It carries data only.
In JavaScript, convert between the two with JSON.parse() and JSON.stringify():
const text = '{"name":"Alice","active":true}';
const value = JSON.parse(text);
const output = JSON.stringify(value, null, 2);
If you already have an object, do not call JSON.parse(object). If you need JSON text, call JSON.stringify(object).
Parsing and Writing JSON in Code
Every major language includes JSON support.
JavaScript:
const raw = '{"name":"Alice","age":30}';
const user = JSON.parse(raw);
const text = JSON.stringify(user);
Python:
import json
raw = '{"name":"Alice","age":30}'
user = json.loads(raw)
text = json.dumps(user)
Go:
package main
import "encoding/json"
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
var user User
_ = json.Unmarshal([]byte(`{"name":"Alice","age":30}`), &user)
}
For files, use a file-aware parser rather than reading chunks and parsing too early. In Python, json.load(file) reads JSON from a file object, while json.loads(text) parses a string.
What JSON Is Used For
JSON is the default data format because it is small enough for machines, readable enough for humans and available in almost every programming language.
Common uses:
- API request and response bodies, often with
Content-Type: application/json. - Webhooks from payment processors, auth providers, and SaaS apps.
- Configuration files for build tools, editors, CLIs, and cloud services.
- Structured logs, often as JSON Lines or NDJSON.
- Data exports from analytics tools, databases, and internal admin systems.
- Messages between services, queues, serverless functions, and workers.
- Test fixtures in application repos.
JSON is well suited for situations where the data is hierarchical and the consumer understands the contract. It does not work well for rich documents, human configuration with lots of comments, binary files, spreadsheet style tables or data that needs strict numeric precision without a documented representation.
JSON in Databases
Modern databases can store JSON directly, but that does not mean every field should become one giant JSON blob.
Practical patterns:
- Store stable fields as normal columns when you filter, join, or sort by them often.
- Store flexible metadata, event properties, integration payloads, or user preferences as JSON.
- Index the JSON paths you query frequently.
- Validate shape at the application boundary before writing messy documents.
Examples by database:
- PostgreSQL has
jsonandjsonb;jsonbis usually better for indexing and containment queries. - MySQL has a native
JSONtype and path functions such asJSON_EXTRACT. - SQLite has JSON functions such as
json_extractandjson_each. - MongoDB stores documents in BSON, a binary JSON-like format with additional types.
Two reminders: JSON object key order is not a safe business rule and duplicate keys should not be used to represent multiple values. Multiple values? Use arrays.
JSON vs XML vs YAML
JSON, XML, and YAML all move structured data, but they feel different in real projects.
| Format | Best fit | Tradeoff |
|---|---|---|
| JSON | APIs, web apps, config consumed by programs | No comments, strict syntax, limited data types |
| XML | Document markup, namespaces, older enterprise protocols | Verbose and heavier to parse |
| YAML | Human-edited config | Indentation and implicit typing can surprise people |
The same user in JSON:
{
"name": "Alice",
"age": 30
}
The same user in XML:
<user>
<name>Alice</name>
<age>30</age>
</user>
JSON has won most web API use cases because it’s compact, maps cleanly to common language data structures, and is built into browser Javascript. XML is still important for document-heavy formats, SOAP, RSS, SAML, and systems that use namespaces. YAML is easier for humans to edit for configuration . But strict JSON is more secure if you have a lot of languages and tools that need to agree on the exact data .
Common JSON Variants
Strict JSON is the baseline. A few related formats show up often:
| Variant | What it changes | How to parse it |
|---|---|---|
| JSONC | Adds comments and usually allows trailing commas | Use a JSONC parser; do not send it as API JSON |
| JSON5 | Adds more JavaScript-like syntax | Convert to strict JSON before interchange |
| NDJSON / JSON Lines | Uses one JSON value per line | Split by line and parse each line |
| JSON Schema | Describes valid JSON shape | Use a schema validator |
| JSON Pointer | Addresses a value inside JSON, such as /users/0/name |
Use it as a path notation, not as JSON itself |
| JSON Patch | Describes changes to JSON documents | Apply operations with a JSON Patch library |
Do not treat these as all the same file format. A tsconfig.json file may allow comments because the TypeScript toolchain parses it as JSONC. A public API response should still be strict JSON.
Common JSON Mistakes
These are the mistakes I would check first when a payload fails:
| Symptom | Example | Fix |
|---|---|---|
| Single quotes | { 'name': 'Alice' } |
Use double quotes |
| Unquoted keys | { name: "Alice" } |
Quote every key |
| Trailing comma | { "a": 1, } |
Remove the final comma |
| Comments | { "a": 1 // note } |
Remove comments or use JSONC where supported |
| Python literals | { "ok": True, "x": None } |
Use true and null |
| Undefined | { "x": undefined } |
Omit the key or use null |
| Two documents together | {} {} |
Wrap in an array or parse as separate messages |
| Raw newline in a string | "line one then a line break |
Use \n |
For pasted examples, JSON Fix can repair common syntax issues locally in your browser. For API contracts and production workflows, fix the producer and validate the result instead of silently accepting malformed data.
Validate Syntax Before You Validate Meaning
JSON syntax validation answers a very narrow question: can this text be read by some strict parser? All of these commands do that first gate:
const value = JSON.parse(rawText);
python3 -m json.tool data.json >/dev/null
jq empty data.json
If it doesn’t parse, fix the syntax or the producer. If parsing succeeds, you have a JSON value, but it is not necessarily useful or safe. This payload is valid JSON:
{
"email": "not-an-email",
"age": -4,
"role": "owner-of-everything"
}
Whether it is valid for your application is a separate question. That is where JSON Schema enters the workflow.
What Is JSON Schema?
JSON Schema is a machine-readable contract for JSON data. It describes which fields are required, which types and values are allowed, how arrays are shaped, and whether or not to accept unknown properties.
The distinction is worth keeping sharp:
| Layer | Question | Typical tool |
|---|---|---|
| JSON parsing | Is this valid JSON text? | JSON.parse, json.loads, jq |
| JSON Schema | Does the parsed value match the documented shape? | Ajv, Python jsonschema |
| Business validation | Is this action allowed and meaningful right now? | Application code, database, authorization rules |
JSON Schema is itself JSON. This Draft 2020-12 schema describes a small user record:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "email", "role"],
"properties": {
"id": {
"type": "string",
"pattern": "^usr_[0-9]+$"
},
"email": {
"type": "string",
"format": "email"
},
"role": {
"enum": ["admin", "editor", "viewer"]
}
},
"additionalProperties": false
}
This value matches it:
{
"id": "usr_42",
"email": "ada@example.com",
"role": "admin"
}
The schema turns several assumptions into executable rules: all three fields must exist, id follows a known pattern, role comes from a fixed list, and unexpected fields are rejected.
JSON Schema Keywords You Will Use First
Most practical schemas start with a small vocabulary.
| Keyword | What it controls | Common mistake |
|---|---|---|
$schema |
The schema draft or dialect | Omitting it and letting tools guess |
type |
The JSON value type | Forgetting that integer excludes decimals |
properties |
Rules for named object fields | Assuming it makes those fields required |
required |
Keys that must be present | Defining important fields only in properties |
items |
Rules for array elements | Forgetting to constrain nested objects |
enum |
A fixed set of allowed values | Using it for a list that changes frequently |
additionalProperties |
Whether unknown object keys are allowed | Closing public response objects too aggressively |
$defs and $ref |
Reusable schema fragments | Changing a shared $id without treating it as breaking |
properties and required solve different problems. This schema does not require email:
{
"type": "object",
"properties": {
"email": { "type": "string" }
}
}
It means only that email must be a string if it appears. Add "required": ["email"] when presence matters.
For nullable values in standalone JSON Schema, list both types:
{
"type": ["string", "null"]
}
Do not assume that default inserts missing data. In JSON Schema, it is an annotation unless your validator has an explicit, non-standard mutation option.
Validate a Schema in JavaScript
Ajv is a common validator in JavaScript and TypeScript projects. For Draft 2020-12, use its matching constructor:
npm install ajv ajv-formats
import Ajv2020 from "ajv/dist/2020.js";
import addFormats from "ajv-formats";
const ajv = new Ajv2020({ allErrors: true });
addFormats(ajv);
const schema = {
$schema: "https://json-schema.org/draft/2020-12/schema",
type: "object",
required: ["id", "email"],
properties: {
id: { type: "string" },
email: { type: "string", format: "email" }
},
additionalProperties: false
};
const validate = ajv.compile(schema);
const data = { id: "usr_42", email: "ada@example.com" };
if (!validate(data)) {
console.error(validate.errors);
}
Compile the schema once and reuse the validation function. In forms, tests, and developer tools, allErrors: true gives the reader a useful list instead of making them fix one field per run.
Validate a Schema in Python
Python's jsonschema package supports Draft 2020-12 validators:
pip install jsonschema
from jsonschema import Draft202012Validator, FormatChecker
schema = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"type": "object",
"required": ["id", "email"],
"properties": {
"id": {"type": "string"},
"email": {"type": "string", "format": "email"},
},
"additionalProperties": False,
}
data = {"id": "usr_42", "email": "ada@example.com"}
validator = Draft202012Validator(schema, format_checker=FormatChecker())
errors = sorted(validator.iter_errors(data), key=lambda error: error.path)
for error in errors:
print(list(error.path), error.message)
Using iter_errors makes sense when you need to report every bad field. A single validate() call is fine when failing fast is the desired behavior.
Schema Validation Is Not Authorization
A perfect schema cannot prove that an email has mail, that a user ID exists, that an SKU is in stock, or that the caller is allowed to change an account. It also doesn’t make a string safe to include in HTML.
Use JSON Schema as a boundary check. Then add authentication, authorization, database lookups, cross-field rules, sanitization, and side-effect controls in application code. Structure is important. It’s not the whole contract.
For quick syntax checks, use JSON Validator. When malformed input contains comments, single quotes, or trailing commas, repair it with JSON Fix before applying a schema. Use JSON Viewer to inspect the parsed shape and How to Format JSON when you need readable output.
Frequently Asked Questions
What does JSON stand for?
JSON is an acronym for JavaScript Object Notation. JSON, despite the name, is language-agnostic. It can be read and written by JavaScript, Python, Go, Java, Ruby, Rust, PHP, databases, CLIs and browsers.
What is JSON used for?
API request and response bodies, webhooks, app configuration, package metadata, structured logs, data exports, test fixtures and messages between services are all written using JSON.
What are the data types in JSON?
JSON has six value types: object, array, string, number, boolean and null. There is no date type . There is no integer type. There is no undefined value. There is no function type. There is no comment type. There is no Map or Set or binary type.
Is JSON the same as a JavaScript object?
No. JSON is text, with a very strict syntax. JavaScript object literal is code. The following features are not supported by JSON but are supported by JavaScript object literal: Comments Trailing commas Unquoted keys Functions Undefined Date objects Computed properties
Can a JSON file start with an array?
Yes. A JSON document can be any JSON value, including an array. Valid JSON is also Arrays , strings , numbers , booleans and null . Objects are common for API responses because they leave room for metadata .
Does JSON support comments?
No. Strict JSON does not allow comments. Some tools use JSONC or JSON5 for human-editable config, but these files need to be converted to strict JSON before being sent across APIs or parsed by normal JSON parsers.
How do I check that JSON is valid?
Use JSON.parse() , python3 -m json.tool , jq empty , or a strict JSON validator. If you need to validate required fields and types, do that with JSON Schema after syntax parsing.
What is the difference between null and a missing key in JSON?
null means the key is there but the value is intentionally empty. If a key is missing, the field was not supplied, not requested, not known, or not applicable. API contracts should record which one they are using.
What is JSON Schema used for?
JSON Schema describes and validates JSON contracts: required fields , allowed types , enums , numeric ranges , array shapes , nested objects and reusable definitions .
Does properties make a field required?
No. properties applies rules when a key exists. Add the key to required when the key must be present.
Does format: "email" always reject bad email strings?
No. Behavior in format depends on the validator and its configuration. If rejection matters, enable format assertions or the validator's format plugin and do not confuse shape checking with deliverability.
Is JSON Schema the same as TypeScript or OpenAPI?
No . TypeScript types are compile time checks inside of TypeScript . OpenAPI is a way to describe HTTP APIs using a dialect of JSON Schema. JSON Schema is a JSON contract. A format for describing the structure of JSON data.
Tools for Working with JSON
- JSON Fix - repair and format pasted JSON locally in your browser.
- JSON Validator - check strict JSON syntax and parser positions.
- JSON Viewer - inspect nested JSON as a collapsible tree.
- JSON Diff - compare two JSON documents.
- JSON vs YAML - choose the right format for config and data interchange.
- JSON to TypeScript - turn JSON samples into TypeScript interfaces.
Sources
- RFC 8259 - the IETF JSON data interchange standard.
- ECMA-404 - Ecma International's JSON data interchange syntax.
- json.org - Douglas Crockford's JSON grammar and overview.
- MDN Working with JSON - browser-focused parsing and serialization examples.
- JSON Schema specification - the current Core and Validation specification links.
- JSON Schema Draft 2020-12 - the declared dialect used in the examples.
- Ajv schema language docs - JavaScript validator draft support and constructors.
- python-jsonschema validation docs - Python validator classes and APIs.
Last reviewed August 2026.