Skip to content

Beginner · How the web and backends work · topic 6 of 54 · 25 min

JSON: the language of APIs

Explanation

JSON (JavaScript Object Notation) is a simple text format for data. Almost every API sends and receives JSON. In JavaScript, JSON.stringify turns an object into JSON text and JSON.parse turns JSON text back into an object. Bad JSON makes JSON.parse throw an error, so always parse outside data inside try and catch.

What JSON is

JSON is plain text that holds data in a fixed, simple shape. It looks like a JavaScript object, but it is only text. Because it is text, any language (JavaScript, Python, Java, Go) can read and write it. That is why APIs use it.

Think of it like this: JSON is like a printed railway reservation form. Everyone in India fills the same boxes in the same order, so any clerk at any station can read it. JSON is one form that every programming language agrees to fill and read the same way.
json
{
  "name": "Asha Verma",
  "age": 24,
  "isStudent": true,
  "skills": ["JavaScript", "SQL"],
  "address": { "city": "Indore", "pin": "452001" },
  "referral": null
}
Valid JSON with every type: string, number, boolean, array, object and null.

The six types

TypeExampleNote
string"Pune"Always double quotes
number42, 99.5, -3No quotes; no NaN or Infinity
booleantrue, falseSmall letters
nullnullMeans "no value"
array[1, 2, 3]An ordered list
object{"key": "value"}Keys must be strings in double quotes

stringify and parse

JSON.stringify(value) turns a JavaScript value into JSON text, ready to send. JSON.parse(text) does the opposite: it reads JSON text and gives you a real object you can use.

javascript
const order = { item: 'Paneer roll', qty: 2, paid: true };

const text = JSON.stringify(order);
console.log(text);        // {"item":"Paneer roll","qty":2,"paid":true}
console.log(typeof text); // string

const back = JSON.parse(text);
console.log(back.qty * 60); // 120

console.log(JSON.stringify(order, null, 2)); // pretty, with 2-space indent
stringify gives text; parse gives an object back. The third argument of stringify adds indentation.

Common mistakes

  • Single quotes: {'name': 'Ravi'} is not JSON. Use double quotes.
  • Trailing comma: {"a": 1,} is not JSON. Remove the last comma.
  • Comments: // and /* */ are not allowed in JSON.
  • Keys without quotes: {name: "Ravi"} is a JavaScript object, but not JSON.
  • undefined and functions are skipped by JSON.stringify; dates become strings.
javascript
function readSettings(text) {
  try {
    return JSON.parse(text);
  } catch (error) {
    console.log('Bad JSON, using defaults:', error.name);
    return { theme: 'light' };
  }
}

console.log(readSettings('{"theme": "dark"}')); // { theme: 'dark' }
console.log(readSettings("{'theme': 'dark'}")); // prints a SyntaxError note, then { theme: 'light' }
JSON.parse throws a SyntaxError on bad text. try and catch stop the crash.
Careful: JSON.parse on text from outside (a request body, a file, another API) can throw an error. If you do not catch it, one bad request can crash your handler. Always wrap it in try and catch.
Tip: JSON.stringify drops keys whose value is undefined. If you want a key to appear with no value, set it to null instead.

Watch the lesson

JSON: the language of APIs · 1/6

JSON = data as text

JSON is a simple text format for data. Almost every API speaks JSON.

Prefer a video by a teacher? Find free videos on “json explained for beginners javascript parse stringify” on YouTube ↗

In real life: A UPI payment status from a payment API

When a payment finishes, the payment company calls your backend with a JSON body like the one below. Your server parses it, checks the status and amount, and marks the order paid. If the text is broken, your server must not crash; it answers 400 and logs the problem.

javascript
const body = '{"orderId": "ORD-7781", "amount": 349, "status": "SUCCESS", "upiRef": "412345678901"}';

let payment;
try {
  payment = JSON.parse(body);
} catch (error) {
  payment = null;
}

if (payment && payment.status === 'SUCCESS') {
  console.log('Mark ' + payment.orderId + ' as paid: Rs ' + payment.amount);
} else {
  console.log('Answer 400: bad or failed payment data');
}
Parse safely, then use the fields.

Practice (0/3 done)

Task 1 · Code · Javascript

Write a function safeParse(text) that returns { ok: true, value } when text is valid JSON, and { ok: false, error } when it is not, where error is the error message (a string). It must never throw.

Task 2 · Code · Javascript

Write a function jsonResponse(status, data) that returns a response object { status, headers: { "Content-Type": "application/json" }, body } where body is data turned into JSON text.

Task 3 · Code · Javascript

A kirana app sends a bill as JSON text: a list of items like [{"item": "Milk", "price": 30, "qty": 2}]. Write a function billTotal(text) that returns the total (price times qty, added up). If the text is not valid JSON or not a list, return 0.

Quick quiz

Question 1

1.Which of these is valid JSON?

Question 2

2.What does JSON.stringify({ a: 1 }) return?

Question 3

3.What happens when JSON.parse gets broken text?

Question 4

4.Which value is NOT a JSON type?

Question 5

5.Why do APIs use JSON?

Read more (free)

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

← Previous: HTTP headers and cookies