What Is JSON? Full Form, Format, Syntax and Examples

What Is JSON? Full Form, Format, Syntax and Examples

Short answer: the full form of JSON is JavaScript Object Notation. It is a plain-text format for storing and sending data as name/value pairs and ordered lists. Douglas Crockford popularised it in the early 2000s, and it is pronounced like the name "Jason". Today it is defined by two matching standards, ECMA-404 and RFC 8259. It uses the file extension .json and the media type application/json.

This guide covers the JSON format, its exact syntax rules and a valid vs invalid examples table. It then compares JSON with JavaScript objects, XML and YAML, and shows how to read and write JSON in JavaScript and Python. Every code example below was run, and its real output is shown under it.

What does JSON stand for?

JSON stands for JavaScript Object Notation. Each word tells you something:

  • JavaScript: the syntax was borrowed from JavaScript's object literals, the { ... } and [ ... ] you write in JS code.
  • Object: the main building block is an object, a set of names (keys) paired with values.
  • Notation: it is only a way of writing data down as text. It is not a programming language. It has no variables, loops or functions.

The name says "JavaScript", but JSON is language-independent. RFC 8259 calls it "a lightweight, text-based, language-independent data interchange format". A Python, Java, Go or C# program can read JSON written by a JavaScript program, and the other way round.

"Data interchange" just means moving data between programs. Think of JSON as a shared language that two programs agree to speak, even when they are written in different languages.

Who created JSON, and how do you pronounce it?

JSON is credited to Douglas Crockford. He describes it as a discovery rather than an invention. In his 2006 talk "JSON: The Fat-Free Alternative to XML", he wrote that several people had independently noticed something. JavaScript object literals were a good way to send data across a network. He made his own discovery in April 2001, while he was CTO of a company called State Software. In 2002 he acquired the json.org domain and put up a page describing the format.

On pronunciation, the ECMA-404 standard has a footnote on the word JSON: "Pronounced /ˈdʒeɪ·sən/, as in 'Jason and The Argonauts'". So "Jason" is the official answer. You will still hear "jay-sawn" in many offices, and everyone will understand you either way.

Here is how JSON went from a web page to a formal standard:

YearMilestone
2001Crockford's "discovery" of the format at State Software (April)
2002json.org goes up with a description of the format
2006RFC 4627 (July), written by Crockford, describes JSON and registers the application/json media type
2009ECMAScript 5th edition adds the JSON grammar and the built-in JSON.parse and JSON.stringify to JavaScript
2013ECMA-404, 1st edition (October): "The JSON Data Interchange Syntax"
2017ECMA-404, 2nd edition, and RFC 8259 (both December). The two define the same grammar

The ECMA-404 standard also says that, because JSON is so simple, "it is not expected that the JSON grammar will ever change". That stability is a big reason it is everywhere.

What JSON looks like

Here is a small JSON document describing a student:

{
  "name": "Asha Rao",
  "age": 21,
  "cgpa": 8.7,
  "isEnrolled": true,
  "mentor": null,
  "skills": ["Java", "SQL", "React"],
  "address": {
    "city": "Pune",
    "pin": "411001"
  }
}

Read it like this:

  • The outer { } is an object. It holds name/value pairs, also called members.
  • Each pair is a name in double quotes, a colon, then a value: "age": 21.
  • Pairs are separated by commas.
  • "skills" holds an array: an ordered list inside [ ].
  • "address" holds another object. Objects and arrays can nest inside each other as deep as you need.
  • "pin" is stored as a string, not a number, on purpose. A PIN code is an identifier, not something you do maths with. Numbers in JSON also cannot have a leading zero, so a code like 0411 would be invalid as a number.

That is the whole idea. json.org says JSON is built on just two structures: a collection of name/value pairs and an ordered list of values. Almost every programming language already has both. In Python they are a dict and a list. In Java they are usually a Map and a List.

JSON format: the 6 data types

RFC 8259 says JSON can represent four primitive types (strings, numbers, booleans and null) and two structured types (objects and arrays). That makes six data types. A boolean is written as one of the two literals true and false:

TypeExampleRules
String"Pune"Double quotes only. Escape " as \" and \ as \\. Control characters such as a raw tab or newline must be escaped (\t, \n)
Number21, -3.5, 6.02e23Base 10 only. No leading zeros, no + sign in front, no hex, no NaN or Infinity. A decimal point needs a digit on both sides
Object{"city": "Pune"}Names must be strings in double quotes. Names should be unique
Array["Java", 42, true]Ordered. Values inside can be of different types
Booleantrue, falseLowercase only. True and TRUE are invalid
NullnullLowercase only. Means "no value"

There is no date type, no undefined, and no separate integer type. Dates are usually sent as strings such as "2026-11-18T09:30:00.000Z", and the receiving program decides how to read them.

On numbers, RFC 8259 adds a practical warning. Software that uses 64-bit floating point numbers (JavaScript does) agrees exactly only on integers between −(2^53 − 1) and 2^53 − 1. That is why many APIs send very large IDs as strings.

JSON syntax rules

These rules come from RFC 8259 and ECMA-404. Break any one of them and a strict parser will reject the whole document.

  1. Strings and names use double quotes. Single quotes cannot wrap a string or a name (an apostrophe inside a string, as in "it's", is fine).
  2. Every name is a string. {name: "Asha"} is valid JavaScript but invalid JSON.
  3. A colon separates a name from its value. A comma separates one member or element from the next.
  4. No trailing commas. [1, 2,] and {"a": 1,} are invalid.
  5. No comments. Neither // nor /* */ is part of the grammar.
  6. Only these values exist: string, number, object, array, true, false, null. So undefined, NaN, Infinity, functions and dates are not JSON values.
  7. The literals are lowercase: true, false, null.
  8. Whitespace between tokens is ignored. Spaces, tabs, line feeds and carriage returns are all fine there. Pretty-printed and one-line JSON mean the same thing.
  9. The top level can be any value. Older specs said a JSON text had to be an object or an array. RFC 8259 allows any value, so "hello", 42 and null are complete JSON texts too.
  10. Use UTF-8 when sending JSON between systems. RFC 8259 says JSON exchanged outside a closed ecosystem MUST be UTF-8. It also says not to add a byte order mark at the start.

One rule is softer than the rest. RFC 8259 says names inside an object SHOULD be unique. If they are not, different parsers behave differently: many keep the last value, some throw an error. JavaScript's JSON.parse keeps the last one, as the ECMAScript spec requires. Do not rely on it.

Valid vs invalid JSON examples

Each row below was checked by running it through JSON.parse in Node.js.

JSON textValid?Why
{"name": "Asha", "age": 21}ValidQuoted names, string and number values
["Java", 42, true, null]ValidArrays can mix value types
"hello"ValidA single value is a complete JSON text
{}ValidAn empty object is fine
{'name': 'Asha'}InvalidSingle quotes
{name: "Asha"}InvalidName is not in double quotes
{"a": 1,}InvalidTrailing comma in an object
[1, 2,]InvalidTrailing comma in an array
{"a": 1} // noteInvalidComments are not allowed
{"price": NaN}InvalidNaN is not a JSON number
{"x": undefined}Invalidundefined is not a JSON value
{"ok": True}InvalidLiterals must be lowercase
{"pin": 0411}InvalidNumbers cannot have a leading zero
{"half": .5}InvalidA digit must come before the decimal point
{"color": 0xFF}InvalidHexadecimal numbers are not allowed
{"a": 1 "b": 2}InvalidMissing comma between members
{"a": 1, "a": 2}Valid, but avoidDuplicate names. JavaScript keeps the last value

You can test any snippet the same way. Here is a tiny checker:

const samples = ['{"ok": true}', "{'ok': true}", '[1, 2,]', '42'];

for (const text of samples) {
  try {
    JSON.parse(text);
    console.log("valid  ", text);
  } catch {
    console.log("invalid", text);
  }
}
valid   {"ok": true}
invalid {'ok': true}
invalid [1, 2,]
valid   42

JSON structure: nesting and reading values

Real JSON is usually nested: objects inside arrays inside objects. Once you parse it, you read values with the normal dot and bracket syntax of your language.

const text = `{
  "name": "Asha Rao",
  "age": 21,
  "mentor": null,
  "skills": ["Java", "SQL", "React"],
  "address": { "city": "Pune", "pin": "411001" },
  "projects": [
    { "title": "Library system", "stars": 12 },
    { "title": "Weather app", "stars": 30 }
  ]
}`;

const student = JSON.parse(text);
console.log(student.name);
console.log(student.skills[1]);
console.log(student.address.city);
console.log(student.projects[1].title);
console.log(typeof student.age, student.mentor);
Asha Rao
SQL
Pune
Weather app
number null

Before JSON.parse, text is just a string. You cannot do text.name. After parsing, student is a normal JavaScript object.

JSON vs a JavaScript object literal

This is the most common confusion for beginners. JSON looks like JavaScript, but most JavaScript is not JSON. MDN puts it plainly: JSON "is based upon JavaScript syntax, but is distinct from JavaScript".

JSONJavaScript object literal
What it isA string of textA live value in memory
Names (keys)Must be double-quoted stringsCan be unquoted, single-quoted or computed
String quotesDouble onlySingle, double or backticks
Trailing commasNot allowedAllowed
CommentsNot allowedAllowed
Valuesstring, number, object, array, true, false, nullAnything, including functions, undefined, Date, NaN, Symbol, BigInt

The easiest way to see the gap is to convert a JavaScript object to JSON and look at what survives:

const course = {
  title: 'Backend basics',        // single quotes and an unquoted key: fine in JS
  hours: 40,
  start: new Date(Date.UTC(2026, 0, 5)),
  mentor: undefined,
  fee: NaN,
  certificate() { return "PDF"; },
  [Symbol("id")]: 7,
  tags: ["node", undefined, () => {}],
};

console.log(JSON.stringify(course));
{"title":"Backend basics","hours":40,"start":"2026-01-05T00:00:00.000Z","fee":null,"tags":["node",null,null]}

Look at what happened:

  • The Date became a plain string in ISO format.
  • mentor (undefined), the certificate function and the Symbol key disappeared.
  • NaN became null.
  • Inside the array, undefined and the function became null, so the array keeps its length.

JSON.parse and JSON.stringify in JavaScript

JavaScript has a built-in JSON object with two main methods:

  • JSON.parse(text) turns a JSON string into a JavaScript value. This is called parsing or deserialising.
  • JSON.stringify(value) turns a JavaScript value into a JSON string. This is called serialising.

Serialising means turning data in memory into text (or bytes) you can save or send. Deserialising is the reverse. JSON is one serialisation format, and a very popular one.

JSON.stringify: indentation and the replacer

JSON.stringify takes up to three arguments: JSON.stringify(value, replacer, space).

const user = { id: 101, name: "Ravi", password: "s3cret", roles: ["admin", "dev"] };

// 1. Pretty-print with 2 spaces of indentation
console.log(JSON.stringify(user, null, 2));

// 2. A replacer array keeps only the listed keys
console.log(JSON.stringify(user, ["id", "name"]));

// 3. A replacer function can drop or change values
console.log(JSON.stringify(user, (key, value) => (key === "password" ? undefined : value)));
{
  "id": 101,
  "name": "Ravi",
  "password": "s3cret",
  "roles": [
    "admin",
    "dev"
  ]
}
{"id":101,"name":"Ravi"}
{"id":101,"name":"Ravi","roles":["admin","dev"]}

The space argument can be a number or a string. MDN notes that numbers above 10 are treated as 10, and strings are cut to their first 10 characters. Returning undefined from a replacer function removes that property. That is a handy way to keep secrets such as passwords out of logs.

JSON.parse: the reviver and dates

JSON.parse(text, reviver) takes an optional reviver function. It sees every key and value after parsing and can swap in a new value. The classic use is turning date strings back into Date objects, because JSON has no date type.

const text = '{"orderId": 5001, "placedAt": "2026-11-18T09:30:00.000Z"}';

const plain = JSON.parse(text);
console.log(typeof plain.placedAt);

const revived = JSON.parse(text, (key, value) =>
  key === "placedAt" ? new Date(value) : value
);
console.log(revived.placedAt instanceof Date, revived.placedAt.getUTCHours());
string
true 9

So JSON.stringify turns a Date into a string. It calls the date's toJSON() method, which returns the same text as toISOString(). But JSON.parse will not turn it back on its own. You have to do that step.

What JSON.stringify cannot handle

Two kinds of values make JSON.stringify throw an error instead of quietly dropping them: BigInt values and circular references. A circular reference is an object that points back to itself, directly or through other objects.

try {
  JSON.stringify({ followers: 12345678901234567890n });
} catch (err) {
  console.log(err.name + ": " + err.message);
}

const node = { name: "A" };
node.self = node;                 // the object now contains itself
try {
  JSON.stringify(node);
} catch (err) {
  console.log(err.name + ": " + err.message);
}
TypeError: Do not know how to serialize a BigInt
TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'Object'
    --- property 'self' closes the circle

Both are TypeErrors, as the ECMAScript spec requires. The message text above is what Node.js 23 (the V8 engine) prints. Firefox words the BigInt one as "BigInt value can't be serialized in JSON", according to MDN.

Here is the full list of what JSON.stringify does with values JSON cannot represent:

ValueInside an objectInside an arrayOn its own
undefined, function, SymbolProperty is left outBecomes nullReturns undefined
NaN, Infinity, -InfinityBecomes nullBecomes null"null"
DateISO date stringISO date stringISO date string
BigIntThrows TypeErrorThrows TypeErrorThrows TypeError
Circular referenceThrows TypeErrorThrows TypeErrorn/a

This is also why the old trick JSON.parse(JSON.stringify(obj)) is a poor way to copy objects: it loses dates, functions and undefined. Our post on deep cloning objects in JavaScript covers better options.

Common JSON errors: "Unexpected token" and friends

When JSON.parse gets text that breaks the rules, it throws a SyntaxError. These are the messages Node.js 23 prints for the mistakes people make most often:

const broken = [
  "{'name': 'Asha'}",                   // single quotes
  '{"a": 1,}',                          // trailing comma
  '{"ok": True}',                       // capital T
  '{"a": 1',                            // missing closing brace
  "",                                   // empty response body
  "undefined",                          // a JS value, not JSON
  "<!DOCTYPE html><html>...</html>",    // got an HTML page instead of JSON
];

for (const text of broken) {
  try {
    JSON.parse(text);
  } catch (err) {
    console.log(err.name + ": " + err.message);
  }
}
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
SyntaxError: Expected double-quoted property name in JSON at position 8 (line 1 column 9)
SyntaxError: Unexpected token 'T', "{"ok": True}" is not valid JSON
SyntaxError: Expected ',' or '}' after property value in JSON at position 7 (line 1 column 8)
SyntaxError: Unexpected end of JSON input
SyntaxError: "undefined" is not valid JSON
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

How to read them:

  • "Unexpected token '<'" almost always means the server sent back an HTML page (often an error or login page) instead of JSON. Check the URL, the status code and the Content-Type header of the response.
  • "Unexpected end of JSON input" means the text stopped early. The usual causes are an empty response body or a missing closing } or ].
  • "Expected property name" or "Expected double-quoted property name" points to single quotes, unquoted keys or a trailing comma.
  • The position number is a zero-based index into the string. Count from 0 to find the character that broke the parse.

The wording of these messages comes from the JavaScript engine, so Chrome, Firefox and Safari word them differently. The fix is the same.

JSON in REST APIs

A REST API is a web service that you talk to with plain HTTP requests (GET, POST, PUT, DELETE) on URLs. Most REST APIs today send and receive JSON in the request and response bodies. If APIs are new to you, start with our explainer on what an API is.

Two headers matter:

  • Content-Type: application/json on a request or response says "the body is JSON". This media type is registered by RFC 8259.
  • Accept: application/json on a request says "please reply in JSON".

You will often see application/json; charset=utf-8. RFC 8259 defines no charset parameter for this media type. It says adding one has no effect on compliant receivers, because JSON sent between systems must be UTF-8 anyway.

In the browser and in Node.js 18+, you call an API with fetch(). The example below builds a fake server reply locally with Response, so it runs without any network. A real call works the same way: const res = await fetch(url) gives you the same kind of Response object.

// A stand-in for a server reply, so this runs offline
const res = new Response('{"id": 1, "title": "Learn JSON", "done": false}', {
  headers: { "Content-Type": "application/json" },
});
console.log(res.headers.get("Content-Type"));
const todo = await res.json();          // reads the body and runs JSON.parse on it
console.log(todo.title, todo.done);

// Building a POST request with a JSON body (created, not sent)
const req = new Request("https://api.example.com/todos", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ title: "Practise JSON.parse", done: false }),
});
console.log(req.method, req.headers.get("Content-Type"));
console.log(await req.text());

// When the server sends HTML instead of JSON, res.json() fails the same way JSON.parse does
const htmlPage = new Response("<!DOCTYPE html><p>Login required</p>");
try {
  await htmlPage.json();
} catch (err) {
  console.log(err.name + ": " + err.message);
}
application/json
Learn JSON false
POST application/json
{"title":"Practise JSON.parse","done":false}
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Note that res.json() does not return JSON. As MDN points out, it returns a promise of the parsed JavaScript value. Also note that you must call JSON.stringify yourself on the request body: fetch will not do it for you.

This code uses top-level await, so save it as a .mjs file if you run it in Node.js.

JSON in Python

Python's standard library has a json module. The two functions you will use most are json.loads (load from a string) and json.dumps (dump to a string). json.load and json.dump, without the "s", do the same with files.

import json

text = '{"name": "Asha", "age": 21, "isEnrolled": true, "mentor": null, "skills": ["Java", "SQL"]}'
student = json.loads(text)
print(student)
print(type(student).__name__, student["skills"][0])

data = {"course": "DSA", "price": 0, "live": False, "tags": ("arrays", "graphs")}
print(json.dumps(data))
print(json.dumps(data, indent=2, sort_keys=True))
{'name': 'Asha', 'age': 21, 'isEnrolled': True, 'mentor': None, 'skills': ['Java', 'SQL']}
dict Java
{"course": "DSA", "price": 0, "live": false, "tags": ["arrays", "graphs"]}
{
  "course": "DSA",
  "live": false,
  "price": 0,
  "tags": [
    "arrays",
    "graphs"
  ]
}

The type mapping, from the Python docs:

JSONPython (after loads)
objectdict
arraylist (a tuple is also written as an array by dumps)
stringstr
numberint or float
true / falseTrue / False
nullNone

One trap: by default, Python is more relaxed than the JSON standard. The docs say json.loads "also understands NaN, Infinity, and -Infinity", which is "outside the JSON spec". And json.dumps writes them out unless you pass allow_nan=False:

import json

print(json.dumps({"score": float("nan")}))

try:
    json.dumps({"score": float("nan")}, allow_nan=False)
except ValueError as err:
    print("ValueError:", err)

try:
    json.loads("{'name': 'Asha'}")
except json.JSONDecodeError as err:
    print("JSONDecodeError:", err)
{"score": NaN}
ValueError: Out of range float values are not JSON compliant: nan
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

That first line is not valid JSON. A JavaScript client calling JSON.parse on it would throw. If your Python service talks to other systems, pass allow_nan=False so bad data fails early on your side.

JSON vs XML

XML (Extensible Markup Language) is the older text format that JSON replaced in most web APIs. Crockford's own json.org page on the topic is titled "JSON: The Fat-Free Alternative to XML". Here is the same data in both:

{"student": {"name": "Asha", "skills": ["Java", "SQL"]}}
<student><name>Asha</name><skills><skill>Java</skill><skill>SQL</skill></skills></student>
const asJson = '{"student":{"name":"Asha","skills":["Java","SQL"]}}';
const asXml = "<student><name>Asha</name><skills><skill>Java</skill><skill>SQL</skill></skills></student>";
console.log("JSON characters:", asJson.length);
console.log("XML characters: ", asXml.length);
JSON characters: 51
XML characters:  90

XML repeats every element name in a closing tag, so it is longer for the same data. The gap depends on the data, so treat this one example as an illustration, not a rule.

JSONXML
Full formJavaScript Object NotationExtensible Markup Language
StandardECMA-404 and RFC 8259W3C XML 1.0 (5th edition, 2008)
Data modelObjects, arrays, strings, numbers, booleans, nullA tree of elements with attributes and text
ArraysBuilt in: [ ]No array type; you repeat an element
Value typesNumbers, booleans and null are distinct from stringsContent is text; a program or schema decides what it means
CommentsNot allowedAllowed: <!-- ... -->
AttributesNoneYes, for example <skill level="2">
Size for the same dataSmaller (no closing tags)Larger
Reading it in JavaScriptJSON.parse is built inNeeds an XML parser
Common useWeb APIs, config files, NoSQL databasesDocuments that mix text and markup, SOAP web services

Pick JSON for APIs and app data. Pick XML for documents with mixed text and markup, or when a system you must work with already speaks XML. SOAP 1.2, for example, defines its messages in XML.

JSON vs YAML, briefly

YAML is another text format, popular for configuration files that people edit by hand. The YAML 1.2 spec says its "primary focus was making YAML a strict superset of JSON". So in principle a JSON document is also valid YAML 1.2.

# YAML allows comments
student:
  name: Asha
  skills:
    - Java
    - SQL
JSONYAML
StructureBraces and bracketsIndentation (it can also use JSON-style brackets)
CommentsNoYes, with #
Quotes on stringsAlways requiredUsually optional
Best forData sent between programsConfig files written by people

Where JSON is used

  • Web and mobile APIs. Request and response bodies, with the application/json media type.
  • Config files. npm's package.json is one example. The npm docs say it "must be actual JSON, not just a JavaScript object literal".
  • Login tokens. A JSON Web Token (JWT) carries its claims "as a JSON object", as defined in RFC 7519. See our guide to secure JWT authentication.
  • Databases. MongoDB works with JSON-like documents. Internally it stores BSON, which MongoDB describes as a "binary representation of JSON". PostgreSQL and MySQL also have JSON column types.

JSON Schema

JSON itself only checks syntax. It cannot say "age must be a number between 0 and 120". JSON Schema fills that gap. It is a vocabulary for describing what a valid document must contain, and the schema itself is written in JSON. Validator libraries then check documents against it. The current version on json-schema.org is 2020-12.

JSON file extension and MIME type

  • File extension: .json
  • Media (MIME) type: application/json
  • Encoding: UTF-8 when exchanged between systems, with no byte order mark

Both the extension and the media type are listed in RFC 8259's IANA registration, and application/json appears in the IANA media types registry. The registration was first made by RFC 4627 in 2006.

Common JSON interview questions

  1. What is the full form of JSON? JavaScript Object Notation.
  2. Name the JSON data types. String, number, object, array, boolean (true/false) and null.
  3. Is JSON the same as a JavaScript object? No. JSON is text with stricter rules. A JavaScript object is a value in memory.
  4. What does JSON.stringify do with undefined and functions? It leaves them out of objects and turns them into null in arrays.
  5. How do you pretty-print JSON? JSON.stringify(value, null, 2) in JavaScript, json.dumps(value, indent=2) in Python.
  6. Why does JSON.parse throw "Unexpected token '<'"? The response was HTML, not JSON.
  7. Can JSON have comments or trailing commas? No to both.
  8. How do you send JSON with fetch? Set Content-Type: application/json and pass JSON.stringify(data) as the body.
  9. What happens when you stringify an object with a circular reference? It throws a TypeError.

FAQ

What is the full form of JSON?

JSON stands for JavaScript Object Notation. It is a text format for storing and exchanging data, built from name/value pairs and ordered lists. Despite the name, it is language-independent. Python, Java, Go, C# and almost every other language can read and write it, using a built-in module or a popular library.

Who created JSON?

Douglas Crockford is credited with JSON. He says he discovered the format in April 2001 while working at State Software, and in 2002 he set up json.org to describe it. He also wrote RFC 4627 in 2006. Today JSON is defined by the ECMA-404 standard and the IETF's RFC 8259.

How do you pronounce JSON?

The ECMA-404 standard says JSON is pronounced like the name "Jason", as in "Jason and the Argonauts". Many developers also say "jay-sawn", and both are widely understood. In an interview, either pronunciation is fine. What matters is that you know the full form and the syntax rules.

Is JSON a programming language?

No. JSON is a data format, not a programming language. It has no variables, conditions, loops or functions. It only describes data: strings, numbers, booleans, null, objects and arrays. You need a programming language such as JavaScript or Python to read JSON, change the data and write it back.

Can JSON have comments?

No. Standard JSON does not allow comments of any kind, so // or /* */ will make JSON.parse throw a SyntaxError. If you need comments in a config file, use a format that allows them, such as YAML. Some tools accept JSON with comments, but that is a tool-specific extension, not JSON.

What is the difference between JSON and a JavaScript object?

JSON is a string of text that follows strict rules: double-quoted names, no trailing commas, no comments, and only six kinds of values. A JavaScript object is a live value in memory that can hold functions, dates and undefined. JSON.parse turns JSON text into an object, and JSON.stringify turns an object into JSON text.

What is the file extension and MIME type of JSON?

A JSON file uses the extension .json, and the official media (MIME) type is application/json. Both are registered with IANA through RFC 8259. When JSON is sent between systems, RFC 8259 requires UTF-8 encoding. An API sets the Content-Type: application/json header so the receiver knows the body is JSON.

Keep going

JSON is the format your code will use to talk to almost every API you build or call. Next, see why a browser blocks some of those calls and how to fix it, in the No 'Access-Control-Allow-Origin' header error. Then practise walking through parsed data with ways to loop over a JavaScript object.

If you want to build real backend and full-stack projects that send and receive JSON every day, with mentors reviewing your code, look at Crio's Software Development Fellowship Program.

You've successfully subscribed to Crio Blog
Great! Next, complete checkout to get full access to all premium content.
Welcome back! You've successfully signed in.
Unable to sign you in. Please try again.
Success! Your account is fully activated, you now have access to all content.
Error! Stripe checkout failed.
Success! Your billing info is updated.
Billing info update failed.