JSON
Introduction
JSON (JavaScript Object Notation) is a lightweight data format used to exchange information between applications. It is based on JavaScript object syntax but is language-independent, meaning almost every programming language can read and write JSON.
JSON is commonly used in APIs, configuration files, and data storage. In JavaScript, JSON can be easily converted to and from objects using built-in methods.
Concepts
- Data is written as key–value pairs.
- Keys must be strings (wrapped in quotes).
- Values can be
strings,numbers,booleans,arrays,objects, ornull. - Cannot contain functions or
undefined.
Examples
// JavaScript object
const student = {
name: "Alice",
age: 25,
isStudent: true
};
// Convert object to JSON string
const jsonStr = JSON.stringify(student);
console.log(jsonStr);
// '{"name":"Alice","age":25,"isStudent":true}'
// Convert JSON string back to object
const parsedObj = JSON.parse(jsonStr);
console.log(parsedObj.name); // "Alice"
// Nested object example
const library = {
books: [
{ title: "1984", author: "George Orwell" },
{ title: "JS Guide", author: "Mozilla" }
]
};
console.log(JSON.stringify(library, null, 2)); // pretty-printed JSON
Converting Between JSON and JavaScript
- Convert object → JSON string:
JSON.stringify(obj) - Convert JSON string → object:
JSON.parse(jsonString)
Differences from JavaScript Objects
- JSON keys must be strings in quotes.
- JSON cannot have methods.
- JSON does not support undefined.
Challenges
1. Create JSON for a book and parse
- Create a JSON string representing a book with
title,author, andyear. - Parse it into an object and print the title.
💡 Show Answer
const bookJSON='{"title":"1984","author":"George Orwell","year":1949}';
const book=JSON.parse(bookJSON);
console.log(book.title);
2. Array to JSON and back
- Convert an array
[10, 20, 30]into JSON and back.
💡 Show Answer
const arr=[10,20,30];
const json=JSON.stringify(arr);
const back=JSON.parse(json);
console.log(back[1]);
3. Car object to JSON
- Create a JavaScript object representing a
car, convert it to JSON, and log the string.
💡 Show Answer
const car={
make:"Toyota",
model:"Corolla"
};
console.log(JSON.stringify(car));
4. Parse JSON string
- Parse the following JSON string and print the student’s course:
{"name":"Bob","age":21,"course":"Math"}
💡 Show Answer
const str='{"name":"Bob","age":21,"course":"Math"}';
const s=JSON.parse(str);
console.log(s.course);
5. toJSONString function
- Write a function
toJSONString(obj)that takes an object and returns its JSON representation.
💡 Show Answer
function toJSONString(obj){
return JSON.stringify(obj);
}
6. Pretty print JSON
- Use
JSON.stringify(obj, null, 2)to pretty-print a nested object.
💡 Show Answer
const user = {
id: 1,
name: "Alice",
address: { city: "Wonderland", zip: "12345" }
};
console.log(JSON.stringify(user.address, null, 2));
7. Stringify object with function
- Show what happens if you try to JSON.stringify an object containing a function.
💡 Show Answer
const obj={
name:"Alice",
greet(){
console.log(`Hello ${this.name}`)
}
};
console.log(JSON.stringify(obj)); // {"name":"Alice"}
8. Compare typeof
- Demonstrate the difference between a plain object and its JSON string using
typeof.
💡 Show Answer
const o={name:"Alice"};
const j=JSON.stringify(o);
console.log(typeof o); // object
console.log(typeof j); // string
9. Safe parse
- Write a function
safeParse(jsonStr)that tries to parse JSON but catches errors if the string is invalid.
💡 Show Answer
function safeParse(str){
try{
return JSON.parse(str);
}
catch{
return null;
}
}
10. Parse library JSON
- Create a JSON object for a
librarywith multiple books (title + author). - Parse it, loop through the books, and print each one.
💡 Show Answer
const lib='{"books":[{"title":"One"},{"title":"Two"}]}';
const l=JSON.parse(lib);
l.books.forEach(
b=>console.log(b.title)
);