- Know the rules of JSON and tell it apart from a JavaScript object
- Convert data with
JSON.stringifyandJSON.parse - Manage errors with
try,catch,finallyandthrow
A weather app gets the forecast for Baku from a server. The server sends it text, not an object — only text can travel over a network. But what if the text arrives cut off or broken? A good program doesn't crash: it catches the problem and shows the user a clear message. In this lesson you will learn both skills.
What is JSON?
JSON (JavaScript Object Notation) is a format for storing and sending data as text. It looks very much like JavaScript objects, but every language understands it: Python, Java, C# and more. Today websites, mobile apps and servers mostly “talk” to each other in JSON.
{
"city": "Baku",
"temperature": 24,
"sunny": true,
"forecast": [25, 27, 22],
"wind": { "speed": 5, "direction": "north" },
"warning": null
}| Feature | JavaScript object | JSON |
|---|---|---|
| Keys | may be unquoted | double quotes only |
| Strings | any quotes | double quotes only |
Functions, undefined | allowed | not allowed |
| Comments, trailing commas | allowed | not allowed |
JSON.stringify and JSON.parse
JSON.stringify turns an object into a JSON string — for sending or saving it. JSON.parse does the opposite: it builds an object again from a JSON string. If you pass 2 as the third argument, stringify lays the text out neatly with indentation.
const weather = { city: 'Baku', temperature: 24, sunny: true };
const text = JSON.stringify(weather);
console.log(text);
console.log(typeof text);
const back = JSON.parse(text);
console.log(back.city, typeof back);
console.log(JSON.stringify({ name: 'Leyla', level: 3 }, null, 2));▸ Expected output
{"city":"Baku","temperature":24,"sunny":true}
string
Baku object
{
"name": "Leyla",
"level": 3
}const profile = {
name: 'Leyla',
nickname: undefined,
greet() { return 'Hi!'; },
born: new Date('2010-05-28'),
};
console.log(JSON.stringify(profile));▸ Expected output
{"name":"Leyla","born":"2010-05-28T00:00:00.000Z"}Errors and try...catch
When something goes wrong while a program runs, JavaScript creates an error (an exception). An error that nobody catches stops the program. The most common kinds are SyntaxError (bad syntax, such as broken JSON), TypeError (an operation that is impossible for a value, such as reading a property of null) and ReferenceError (a variable that doesn't exist).
We put risky code in a try block. If an error happens there, the rest of try is skipped and control jumps to the catch block, which receives the error object. The finally block runs always, whether there was an error or not.
const input = '{ city: Baku }';
try {
const data = JSON.parse(input);
console.log('City:', data.city);
} catch (error) {
console.log('Could not read the data:', error.name);
} finally {
console.log('Check finished');
}
try {
const user = null;
console.log(user.name);
} catch (error) {
console.log('Problem:', error.name);
}▸ Expected output
Could not read the data: SyntaxError Check finished Problem: TypeError
input the key and value have no quotes — that is not JSON. Put city and Baku in double quotes and run the code again.Throwing your own error: throw
Sometimes everything is fine for JavaScript, but your program's logic is broken: for example, someone tries to withdraw more money than the balance. In such cases you create your own error with throw new Error('...'). The code after throw does not run, and the error “flies” up to the nearest catch.
function withdraw(balance, amount) {
if (amount > balance) {
throw new Error('Not enough money');
}
return balance - amount;
}
try {
console.log(withdraw(100, 30));
console.log(withdraw(100, 500));
console.log('This line is never printed');
} catch (error) {
console.log('Error:', error.message);
}▸ Expected output
70 Error: Not enough money
Write a function safeParse(text, fallback) that returns the object when the JSON is valid and the fallback value when it is broken.
Show solutionHide solution
JSON.parse inside try and return the result.If an error happens, the
catch block returns fallback.Such a function shields the rest of the program from errors (see the code).
function safeParse(text, fallback) {
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
console.log(safeParse('[1, 2, 3]', []));
console.log(safeParse('oops', []));
console.log(safeParse('{"score": 90}', {}).score);▸ Expected output
[ 1, 2, 3 ] [] 90
Complete readScore(text): it must read the JSON text and return the score value. If the text is not valid JSON, throw an error with the message 'Invalid JSON'; if the score is not in the range 0–100, throw one with 'Score out of range' (throw new Error(...)). The loop below prints each result or error message.
function readScore(text) {
// 1) JSON.parse inside try...catch → throw new Error('Invalid JSON')
// 2) score outside 0–100 → throw new Error('Score out of range')
// 3) return the score
}
const inputs = ['{"score": 92}', '{"score": 140}', '{score: 50}'];
for (const text of inputs) {
try {
console.log('Score:', readScore(text));
} catch (error) {
console.log('Error:', error.message);
}
}▸ Expected output
Score: 92 Error: Score out of range Error: Invalid JSON
Key points
- JSON is a universal text format for sending data; keys and strings use double quotes.
JSON.stringifyturns an object into text,JSON.parseturns text into an object.tryholds risky code,catchcatches the error,finallyalways runs.throw new Error('...')creates your own error; the code after it does not run.- An error object has
nameandmessage; never swallow errors silently.
Check yourself
10 questions. Every correct answer earns XP.