JSON versus JavaScript

Is JSON JavaScript? No. JSON is a data format derived from JavaScript syntax. Learn the rule differences, what conversion changes, and how to keep JSON valid.

JSON is not JavaScript, although it grew out of it. JSON, short for JavaScript Object Notation, is a text format for exchanging data. It is standardized in ECMA-404 and RFC 8259, and its syntax borrows from JavaScript's object and array literals. JavaScript is a programming language. A JSON document only describes data. It cannot run, declare variables, call functions or refer to anything outside itself. That gap explains most of the confusion, and most of the errors, when people move text between the two.

What actually separates JSON from JavaScript

JSON allows exactly six kinds of value. Anything else, however natural it looks in JavaScript, is outside the format.

  • Objects: unordered collections of name/value pairs in curly braces
  • Arrays: ordered lists in square brackets
  • Strings: always in double quotes
  • Numbers: decimal only, with optional fraction and exponent
  • The literals true and false
  • The literal null

A JavaScript object literal is code that the engine evaluates at runtime. It can contain expressions, function definitions, computed keys, variables, undefined, NaN, Infinity, BigInt values, Symbols, Dates and references to other objects. JSON can represent none of these directly. Because JSON is plain text with a small, fixed grammar, parsers exist for nearly every programming language. That independence from JavaScript is the main reason JSON is used as an interchange format.

Syntax rules that differ

  • Keys: JSON requires double-quoted string keys. JavaScript accepts unquoted identifiers, single quotes and computed keys.
  • Strings: JSON allows only double quotes. JavaScript also accepts single quotes and template literals.
  • Trailing commas: JSON forbids them. JavaScript allows them in object and array literals.
  • Comments: JSON has none. JavaScript supports line and block comments.
  • Numbers: JSON rejects hexadecimal, leading zeros, a leading plus sign, a bare leading or trailing decimal point, NaN and Infinity. JavaScript accepts all of these in source code.
  • Whitespace: outside strings, JSON permits only space, tab, line feed and carriage return.

The illustrative example below shows a JavaScript object that will not parse as JSON, followed by the closest valid JSON equivalent. The function and the undefined property have no JSON form, so they are simply left out.

// Valid JavaScript, not valid JSON
const config = {
  name: 'demo',          // unquoted key, single quotes
  retries: 3,
  timeout: undefined,
  onError() { return null; },
  tags: ['a', 'b',],     // trailing comma
};

// Closest JSON equivalent
{
  "name": "demo",
  "retries": 3,
  "tags": ["a", "b"]
}

Is every JSON document valid JavaScript?

In modern engines, nearly always. Older ECMAScript versions rejected the characters U+2028 and U+2029 inside string literals, while JSON permitted them. The ECMAScript 2019 "JSON superset" change removed that mismatch. One meaningful difference remains: a key named "proto". JSON.parse creates an ordinary own property with that name. The same text written as a JavaScript object literal sets the object's prototype instead.

The fact that JSON is syntactically valid JavaScript is no reason to evaluate it as code. Use JSON.parse, or your language's JSON library, rather than eval. A parser accepts only data. Evaluating untrusted input as code can execute whatever that input contains.

What changes when you convert between them

In JavaScript, JSON.stringify turns values into JSON text and JSON.parse turns JSON text back into values. The round trip is lossless only for data that already fits JSON's six value types. The ECMAScript specification defines the following behavior.

  • Properties whose value is undefined, a function or a Symbol are dropped from objects.
  • The same values inside arrays become null, so array positions are preserved.
  • NaN and Infinity become null.
  • Dates become ISO 8601 strings through their toJSON method. Parsing returns a string, not a Date.
  • BigInt values cause a TypeError unless you supply custom handling.
  • Circular references cause a TypeError.
  • Numbers are parsed as 64-bit floating-point values, so integers beyond 2^53 can silently lose precision.
  • When an object contains duplicate keys, JSON.parse keeps the last value. The JSON standard only says names should be unique, so other parsers may behave differently.

The illustrative snippets below show the documented results of these rules. The output comments come from the specification and were not observed in a particular environment.

JSON.stringify({ a: undefined, b: () => 1, c: NaN, d: new Date(0), e: [undefined] })
// '{"c":null,"d":"1970-01-01T00:00:00.000Z","e":[null]}'

JSON.parse('{"id": 9007199254740993}').id
// 9007199254740992  (precision lost)

JSON.stringify(JSON.parse('{"b":1,"10":2,"a":3}'))
// '{"10":2,"b":1,"a":3}'  (integer-like keys move first)

Which one fits your situation

Criterion | JSON | JavaScript object literal
What it is | Text data format | Source code in a programming language
Executable | No | Yes, evaluated by the engine
Allowed values | Object, array, string, number, true/false, null | Any JavaScript value, including functions, undefined, Dates and BigInt
Comments and trailing commas | Not allowed | Allowed
Key and string quoting | Double quotes required | Flexible
Usable outside JavaScript | Yes, parsers exist for most languages | Only where a JavaScript engine runs
Safe to accept from untrusted sources | Yes, through a parser | No, evaluating it runs code
  • Use JSON for API payloads, stored data, messages between systems and configuration that other tools or languages must read.
  • Use JavaScript objects when you need behavior, computed values, references or types that JSON cannot express, and when the data stays inside one JavaScript program.
  • If you want comments or trailing commas in configuration files, use a format that explicitly supports them, such as a comment-tolerant JSON variant, JSON5 or a JavaScript config module. Confirm that the tool reading the file accepts that format, because strict JSON parsers will reject it.

Keeping JSON valid and readable where you need it

JSON is plain text, so it copies and pastes like any other text. However, JSON is strict, and small changes made in transit can break it. Word processors, chat apps and rich-text editors may replace straight quotes with curly ones. Content pasted from web pages can carry non-breaking spaces, which are not valid JSON whitespace outside strings. A byte order mark at the start of a file can cause strict parsers to reject it. When pasted JSON fails to parse, check for these invisible or substituted characters first.

Validate against the parser that will actually consume the data. Lenient formatters or editors may accept comments, trailing commas or single quotes, so passing one tool does not guarantee that another will accept the file. Pretty-printing and minifying change only the whitespace between tokens, and the meaning stays the same. A formatter that parses the text and then re-serializes it can still alter it, though. It may reorder integer-like keys, collapse duplicate keys or round very large numbers, as shown above. If exact bytes or key order matter, compare the output with the original.

Be careful with sensitive input. A web-based formatter or validator may send your text to a server unless it clearly documents that processing happens locally. Remove API keys, tokens and personal data before pasting, or validate on your own machine. The commands below are common local options. The second requires jq to be installed.

python3 -m json.tool data.json
jq . data.json
node -e "JSON.parse(require('fs').readFileSync('data.json','utf8'))"

Evidence note: this guide relies on the JSON and ECMAScript specifications, not on tests of specific formatting tools. No measurements of particular validators, editors, clipboard handling or screen reader output were available. Check behavior in your own tools and destinations before relying on it.