JavaScript JSON Introduction

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write, and easy for machines to parse and generate. JSON is the most common format for data exchange in web applications.

What is JSON?

JSON is a text format for storing and transporting data. Despite its name, JSON is language-independent and is used by many programming languages, not just JavaScript.

JSON Example
// A JSON string
const jsonString = '{"name": "Alice", "age": 30, "city": "New York"}';
console.log('JSON string: ' + jsonString);
console.log('Type: ' + typeof jsonString);

// Parse it to a JavaScript object
const obj = JSON.parse(jsonString);
console.log('Name: ' + obj.name);
console.log('Age: ' + obj.age);
console.log('City: ' + obj.city);

JSON Syntax Rules

JSON has strict syntax rules that must be followed. Unlike JavaScript objects, JSON requires double quotes around keys and string values.

JSON Syntax
// Valid JSON
const validJSON = '{"name": "Bob", "active": true, "score": 95}';
console.log('Valid: ' + validJSON);

// JSON syntax rules:
// 1. Keys must be double-quoted strings
// 2. String values must use double quotes
// 3. No trailing commas
// 4. No comments allowed
// 5. No single quotes

// Invalid JSON examples:
// {name: "Bob"}        - keys not quoted
// {'name': 'Bob'}       - single quotes
// {"name": "Bob",}    - trailing comma

const parsed = JSON.parse(validJSON);
console.log('Parsed name: ' + parsed.name);
console.log('Parsed active: ' + parsed.active);

JSON Data Types

JSON supports a limited set of data types. Understanding which types are valid in JSON is important for proper serialization.

Data TypeJSON ExampleNotes
String"hello"Must use double quotes
Number42, 3.14, -10No NaN, Infinity, or hex
Booleantrue, falseLowercase only
nullnullLowercase only
Array[1, 2, 3]Ordered list of values
Object{"key": "value"}Key-value pairs
undefinedNOT VALIDNot supported in JSON
FunctionNOT VALIDNot supported in JSON
DateNOT VALID (use string)Store as ISO string
JSON Data Types
const data = {
  string: 'Hello',
  number: 42,
  float: 3.14,
  boolean: true,
  nullValue: null,
  array: [1, 2, 3],
  object: { nested: true }
};

const json = JSON.stringify(data, null, 2);
console.log(json);

JSON vs JavaScript Objects

JSON looks similar to JavaScript object literals, but there are important differences. JSON is a text format (a string), while a JavaScript object is a data structure in memory.

JSON String vs JS Object
// JavaScript object (in memory)
const jsObject = {
  name: 'Alice',
  greet() { return 'Hi!'; }
};

// JSON string (text format)
const jsonStr = '{"name": "Alice"}';

console.log('JS Object type: ' + typeof jsObject);
console.log('JSON string type: ' + typeof jsonStr);
console.log('JS Object name: ' + jsObject.name);
console.log('JSON parse name: ' + JSON.parse(jsonStr).name);

// Functions cannot be in JSON
const withFunc = { name: 'Bob', greet: function() {} };
console.log('Stringified: ' + JSON.stringify(withFunc));
// greet function is omitted!

JSON in APIs and MIME Type

JSON is the standard format for web APIs. When sending or receiving JSON data, the correct MIME type (Content-Type header) is application/json.

JSON in API Communication
// Typical API response (as JSON string)
const apiResponse = JSON.stringify({
  status: 'success',
  data: {
    users: [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' }
    ]
  },
  total: 2
});

console.log('API Response: ' + apiResponse);

// Parsing the response
const result = JSON.parse(apiResponse);
console.log('Status: ' + result.status);
console.log('Total users: ' + result.total);
result.data.users.forEach(function(user) {
  console.log('User: ' + user.name);
});

// MIME type: application/json
console.log('Content-Type: application/json');
📝 Note: JSON was derived from JavaScript object notation syntax but is now language-independent. Its official MIME type is application/json and the file extension is .json. Always validate JSON data from external sources before using it.
Exercise:
Which of the following is NOT a valid JSON data type?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.