Course:Internet & Tools/
Lesson

Every time you fetch data from an APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses., the server replies in a format both sides agree on. That format is almost always JSONWhat is json?A text format for exchanging data between systems. It uses key-value pairs and arrays, and every programming language can read and write it.. It looks like a JavaScript object, but it follows stricter rules so that every programming language, Python, Ruby, Go, Java, can read it without ambiguity.

Think of JSON as the universal adapter for data. It travels between a Node.js backend and a React frontend, between a mobile app and a cloud service, between your browser and every API you will ever call. Learning to read and write JSON fluently is one of the most practical skills you can build right now.

Why JSONWhat is json?A text format for exchanging data between systems. It uses key-value pairs and arrays, and every programming language can read and write it. became the standard

JSON replaced older formats like XML because it solved three problems without introducing new ones.

PropertyWhy it matters
Human readableYou can open a JSON file and understand it immediately
Machine readableEvery language has a built-in JSON parser
LightweightNo wrapping tags, no schema files, just data
Language-agnosticWorks the same in JavaScript, Python, Go, and everywhere else

Before JSON, developers used XML, which looks like HTML with angle brackets everywhere. JSON removed all that ceremony. The same data that took 20 lines of XML fits in 5 lines of JSON.

02

What JSONWhat is json?A text format for exchanging data between systems. It uses key-value pairs and arrays, and every programming language can read and write it. looks like

A JSON document is either an object (curly braces) or an array (square brackets). Here is a simple object describing a user:

json
{
  "name": "Alice",
  "age": 25,
  "isActive": true,
  "email": null,
  "roles": ["admin", "editor"],
  "address": {
    "city": "Boston",
    "country": "US"
  }
}

Every key is a string in double quotes. Every value is one of the six allowed types. Objects and arrays can nest inside each other as deeply as you need.

The six value types

TypeExampleCommon use
String"hello"Names, messages, identifiers
Number42 or 3.14Counts, prices, coordinates
Booleantrue / falseFeature flags, yes/no fields
NullnullExplicitly absent values
Array[1, 2, 3]Lists of anything
Object{"key": "value"}Nested records

Notice what is missing: functions, undefined, dates (dates are just strings in JSON), and comments. If you need those, keep them in your application code, not in the data.

03

AI-generated JSONWhat is json?A text format for exchanging data between systems. It uses key-value pairs and arrays, and every programming language can read and write it. is often malformed

When you ask an AI to produce JSON, whether it is a ChatGPT response, a Copilot suggestion, or output from an LLM-powered APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses., you will frequently receive JSON that looks right but is technically invalid. AI models generate text tokenWhat is token?The smallest unit of text an LLM processes - roughly three-quarters of a word. API pricing is based on how many tokens you use. by token; they do not run a JSON validator before handing you the result.

AI pitfall
AI tools confidently produce JSON with trailing commas, single-quoted keys, inline comments, and JavaScript-style values like undefined. None of these are valid JSON. Always validate AI-generated JSON before trusting it.

The three most common AI-generated JSON mistakes:

Trailing commas

json
// AI loves to leave these in
{
  "name": "Alice",
  "age": 25,
}

That final comma after 25 is illegal. JavaScript objects allow it; JSON does not. AI models trained on JavaScript code carry over this habit constantly.

Comments in JSON

json
{
  "name": "Alice", // the user's display name
  "role": "admin"  /* main administrator */
}

JSON has no comment syntax whatsoever. AI tools insert // and /* */ comments because they are trained on JavaScript and configuration files that support JSONC. Strip all comments before parsing.

Unquoted or single-quoted keys

json
{name: "Alice", 'age': 25}

JSON requires every key to be a double-quoted string. AI models sometimes produce JavaScript object syntax instead of strict JSON, dropping quotes or using single quotes.

Wrong data types

json
{
  "count": "25",
  "active": "true",
  "data": undefined
}

AI may wrap numbers and booleans in quotes (turning them into strings), or use JavaScript's undefined which does not exist in JSON. The correct version is "count": 25, "active": true, and "data": null.

04

Working with JSONWhat is json?A text format for exchanging data between systems. It uses key-value pairs and arrays, and every programming language can read and write it. in JavaScript

JavaScript ships with two methods that handle everything you need: JSON.parse() to decode, and JSON.stringify() to encode.

Parsing a JSON string into an object

When an APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses. sends you data, it arrives as a plain string. You need to parse it before you can use it:

const raw = '{"name": "Alice", "age": 25}';
const user = JSON.parse(raw);

console.log(user.name);  // "Alice"
console.log(user.age);   // 25

After parsing, user is a normal JavaScript object. You can read properties, loop over arrays, and pass it around your code.

Stringifying an object to JSON

When you need to send data to a server or save it to a file, you convert the object back to a string:

const user = { name: "Alice", age: 25 };
const json = JSON.stringify(user);

console.log(json);  // '{"name":"Alice","age":25}'

Pretty-printing for debugging

The compact output above is hard to read. Pass null, 2 as the second and third arguments to add indentation:

const pretty = JSON.stringify(user, null, 2);
console.log(pretty);
/*
{
  "name": "Alice",
  "age": 25
}
*/

The 2 is the number of spaces per indent. Use this whenever you are logging JSON for a human to read.

Always wrap parse in try-catch

JSON.parse() throws a SyntaxError if the input is malformed. Without error handling, a bad API response will crash your application:

try {
  const data = JSON.parse(incomingString);
  // safe to use data here
} catch (error) {
  console.error("Could not parse response:", error.message);
  // handle gracefully
}
Never call JSON.parse() without a try-catch when the source is external, API responses, user input, file contents. You cannot control what arrives.
05

JSONWhat is json?A text format for exchanging data between systems. It uses key-value pairs and arrays, and every programming language can read and write it. vs JavaScript objects

They look almost identical, but they serve different purposes and play by different rules.

RuleJSONJavaScript object
Key quotesRequired (double)Optional
String quotesDouble onlySingle or double
Trailing commasForbiddenAllowed
CommentsNoYes
Functions as valuesNoYes
undefined as valuesNoYes

A JavaScript object is live code that runs in the engine. JSON is inert text that carries data. You pass JSON over a network; you work with JavaScript objects in your code.

06

Quick reference

TaskMethodExample
Decode JSON stringJSON.parse(str)JSON.parse('{"x":1}'){x: 1}
Encode objectJSON.stringify(obj)JSON.stringify({x:1})'{"x":1}'
Encode with indentationJSON.stringify(obj, null, 2)Readable multi-line output
Safe decodetry { JSON.parse(str) } catch (e) {}Handles malformed input
Validate AI outputParse + catch + inspect typesAlways validate before using
javascript
// Working with JSON in JavaScript

// Parsing JSON from API
const response = await fetch('/api/users/1');
const data = await response.json();
console.log(data);
// {"id": 1, "name": "Alice", "email": "alice@example.com"}

// Creating JSON
const user = {
  name: "Bob",
  age: 30,
  hobbies: ["coding", "gaming"],
  address: {
    city: "Boston",
    state: "MA"
  }
};

const jsonString = JSON.stringify(user, null, 2);
console.log(jsonString);
/*
{
  "name": "Bob",
  "age": 30,
  "hobbies": [
    "coding",
    "gaming"
  ],
  "address": {
    "city": "Boston",
    "state": "MA"
  }
}
*/

// Error handling
try {
  const obj = JSON.parse('{invalid json}');
} catch (error) {
  console.error('Invalid JSON:', error.message);
}

// Reading local JSON file (Node.js)
const data = require('./data.json');

// Or with ES modules
import data from './data.json' assert { type: 'json' };