JSON is one of the most common data formats used with JavaScript.
Websites use JSON to exchange product data, user details, settings, search results, form responses, and API data. You will see it often when working with fetch(), local storage, backend services, and modern frontend frameworks.
JSON looks similar to a JavaScript object, but it is not the same thing.
In this lesson, you will learn valid JSON syntax, how to convert JSON text into JavaScript values with JSON.parse(), how to convert JavaScript values into JSON text with JSON.stringify(), and how JSON is used in real websites.
Course Home: JavaScript Tutorial for Beginners
Previous Lesson: JavaScript Form Validation Explained
Next Lesson: JavaScript Fetch API Explained
Quick Answer
JSON stands for JavaScript Object Notation.
JSON is a text format used to store and exchange structured data.
Valid JSON:
{
"name": "Riya",
"age": 28,
"verified": true
}
Convert JSON text into a JavaScript object with:
const jsonText = '{"name":"Riya","age":28}';
const user = JSON.parse(jsonText);
console.log(user.name);
Output:
Riya
Convert a JavaScript object into JSON text with:
const user = {
name: "Riya",
age: 28
};
const jsonText = JSON.stringify(user);
console.log(jsonText);
Output:
{"name":"Riya","age":28}
The two main methods to remember are:
JSON.parse()
JSON.stringify()
What Is JSON?
JSON is a text-based format for representing structured data.
A JSON object can look like this:
{
"product": "Keyboard",
"price": 1500,
"inStock": true
}
This text contains three pieces of information:
- Product name
- Price
- Stock status
JSON is widely used because it is compact, readable, and easy for many programming languages to process.
What Does JSON Stand For?
JSON stands for:
JavaScript Object Notation
The syntax was inspired by JavaScript object syntax.
However, JSON is a data format, not JavaScript code.
Programs written in many languages can create and read JSON.
JSON vs JavaScript Object
This JavaScript object is valid JavaScript:
const product = {
name: "Keyboard",
price: 1500,
inStock: true
};
This is valid JSON:
{
"name": "Keyboard",
"price": 1500,
"inStock": true
}
They look similar, but there are important differences.
In JavaScript object literals, property names do not always need quotes:
{
name: "Keyboard"
}
In JSON, object property names must use double quotes:
{
"name": "Keyboard"
}
JSON Is Text
This is a JavaScript object:
const product = {
name: "Keyboard",
price: 1500
};
This is a JavaScript string containing JSON text:
const jsonText =
'{"name":"Keyboard","price":1500}';
Check the types:
console.log(typeof product);
console.log(typeof jsonText);
Output:
object
string
This difference is essential.
You use JSON.parse() when JSON text needs to become a JavaScript value.
You use JSON.stringify() when a JavaScript value needs to become JSON text.
Why JSON Matters in JavaScript
JSON is common in real frontend development.
You may use it when:
- Receiving API responses
- Sending data to an API
- Saving structured data in localStorage
- Reading configuration files
- Handling server responses
- Storing user preferences
- Moving data between frontend and backend code
- Working with product catalogs
- Loading dashboard data
If you plan to work with APIs, JSON is a core JavaScript skill.
Valid JSON Data Types
JSON supports these main value types:
- String
- Number
- Boolean
- Null
- Object
- Array
Example:
{
"name": "Amit",
"age": 30,
"verified": true,
"middleName": null,
"skills": ["HTML", "CSS", "JavaScript"],
"address": {
"city": "Noida",
"country": "India"
}
}
This one JSON object contains several supported data types.
JSON Strings
JSON strings use double quotes.
Valid:
{
"name": "Riya"
}
Not valid JSON:
{
'name': 'Riya'
}
Single quotes are not valid JSON string delimiters.
JavaScript itself allows strings with single quotes, but JSON syntax does not.
JSON Numbers
JSON can store numbers:
{
"price": 1500,
"rating": 4.5,
"discount": -100
}
Do not place quotes around a value when you want it to be a number.
Number:
{
"price": 1500
}
String:
{
"price": "1500"
}
These represent different data types.
Review JavaScript Data Types if you need a refresher.
JSON Booleans
JSON uses lowercase:
true
and:
false
Example:
{
"inStock": true,
"featured": false
}
Do not write:
True
False
Those are not valid JSON boolean values.
JSON null
JSON supports:
null
Example:
{
"profilePhoto": null
}
This can represent an intentionally empty value.
JSON does not have an undefined value.
JSON Arrays
JSON arrays use square brackets.
Example:
{
"colors": [
"Black",
"White",
"Blue"
]
}
An entire JSON document can also be an array:
[
"HTML",
"CSS",
"JavaScript"
]
After parsing, this becomes a JavaScript array.
JSON Objects
JSON objects use curly braces and key-value pairs.
Example:
{
"name": "Laptop",
"price": 50000
}
Every key must be a double-quoted string.
Values can be strings, numbers, booleans, null, arrays, or other JSON objects.
Nested JSON
JSON can contain nested objects.
Example:
{
"name": "Riya",
"address": {
"city": "Delhi",
"pinCode": 110001
}
}
After parsing, access the nested city with:
user.address.city
Nested JSON is common in real API responses.
Arrays of JSON Objects
Product APIs often return arrays of objects.
Example:
[
{
"id": 1,
"name": "Keyboard",
"price": 1500
},
{
"id": 2,
"name": "Mouse",
"price": 700
}
]
After parsing, JavaScript receives an array containing objects.
That structure works naturally with JavaScript Arrays and JavaScript Objects.
JSON Syntax Rules
Valid JSON follows several important rules.
Property Names Need Double Quotes
Valid:
{
"name": "Riya"
}
Invalid:
{
name: "Riya"
}
Strings Need Double Quotes
Valid:
{
"city": "Delhi"
}
Invalid:
{
"city": 'Delhi'
}
No Trailing Commas
Invalid JSON:
{
"name": "Riya",
"age": 28,
}
Valid JSON:
{
"name": "Riya",
"age": 28
}
JavaScript object literals may allow trailing commas in many places, but JSON does not.
No Comments
This is not valid JSON:
{
"name": "Riya",
// User age
"age": 28
}
Standard JSON does not support comments.
Use Lowercase true, false and null
Valid:
{
"active": true,
"deleted": false,
"photo": null
}
Values JSON Does Not Directly Support
Standard JSON does not directly represent JavaScript values such as:
undefined
functions
Symbol
BigInt
NaN
Infinity
-Infinity
Some of these are omitted or changed by JSON.stringify().
BigInt causes JSON.stringify() to throw unless you convert it to a supported representation first.
We will look at these cases later in the lesson.
What Is JSON.parse()?
JSON.parse() converts valid JSON text into a JavaScript value.
Example:
const jsonText =
'{"name":"Riya","age":28}';
const user = JSON.parse(jsonText);
console.log(user);
Now user is a JavaScript object.
Check:
console.log(typeof user);
Output:
object
JSON.parse() Syntax
The basic syntax is:
JSON.parse(jsonString);
Example:
const data = JSON.parse('{"price":1500}');
console.log(data.price);
Output:
1500
Parse a JSON Array
Example:
const jsonText =
'["HTML","CSS","JavaScript"]';
const skills = JSON.parse(jsonText);
console.log(skills[0]);
Output:
HTML
Check whether it is an array:
console.log(Array.isArray(skills));
Output:
true
Parse Nested JSON
Example:
const jsonText = `
{
"name": "Amit",
"address": {
"city": "Noida"
}
}
`;
const user = JSON.parse(jsonText);
console.log(user.address.city);
Output:
Noida
Once parsed, normal JavaScript object rules apply.
What Happens With Invalid JSON?
JSON.parse() throws an error when the JSON text is invalid.
Example:
const invalidJson =
'{"name":"Riya",}';
const user = JSON.parse(invalidJson);
The trailing comma makes the JSON invalid.
JavaScript throws a SyntaxError.
Handle JSON.parse() Errors With try…catch
When JSON may be invalid, use:
try {
const data = JSON.parse(jsonText);
console.log(data);
} catch (error) {
console.log("Invalid JSON");
}
This prevents the parsing error from stopping the rest of your code unexpectedly.
You will study try...catch in more detail in the JavaScript error-handling lesson.
Real Website Example: Parse Product Data
Suppose a server response is represented as JSON text:
const responseText = `
{
"id": 101,
"name": "Keyboard",
"price": 1500,
"inStock": true
}
`;
Parse it:
const product = JSON.parse(responseText);
Now use the data:
console.log(product.name);
console.log(product.price);
Output:
Keyboard
1500
What Is JSON.stringify()?
JSON.stringify() converts a JavaScript value into JSON text.
Example:
const user = {
name: "Riya",
age: 28
};
const jsonText = JSON.stringify(user);
console.log(jsonText);
Output:
{"name":"Riya","age":28}
The result is a string.
Check:
console.log(typeof jsonText);
Output:
string
JSON.stringify() Syntax
The basic syntax is:
JSON.stringify(value);
Example:
const product = {
name: "Mouse",
price: 700
};
const json = JSON.stringify(product);
Stringify an Array
Example:
const skills = [
"HTML",
"CSS",
"JavaScript"
];
const json = JSON.stringify(skills);
console.log(json);
Output:
["HTML","CSS","JavaScript"]
Stringify Nested Objects
Example:
const user = {
name: "Amit",
address: {
city: "Noida",
country: "India"
}
};
const json = JSON.stringify(user);
console.log(json);
The nested object is included in the JSON text.
Pretty Print JSON
By default, JSON.stringify() creates compact JSON.
You can add indentation:
const user = {
name: "Riya",
age: 28
};
const json = JSON.stringify(
user,
null,
2
);
console.log(json);
Output:
{
"name": "Riya",
"age": 28
}
The third argument controls indentation.
This is useful for debugging and readable files.
JSON.stringify() Arguments
The method can receive:
JSON.stringify(value, replacer, space);
For most beginner work:
JSON.stringify(value)
is enough.
For readable output:
JSON.stringify(value, null, 2)
is useful.
Select Properties With a Replacer Array
You can choose which object properties appear.
Example:
const user = {
name: "Riya",
age: 28,
password: "secret"
};
const json = JSON.stringify(
user,
["name", "age"]
);
console.log(json);
Output:
{"name":"Riya","age":28}
The password property is not included in that output.
Do not treat this as a security system. Sensitive data should not be exposed to frontend code unless it genuinely belongs there.
JSON.stringify() With undefined
Consider:
const user = {
name: "Riya",
city: undefined
};
console.log(JSON.stringify(user));
Output:
{"name":"Riya"}
The object property containing undefined is omitted.
Inside an array:
console.log(
JSON.stringify([1, undefined, 3])
);
Output:
[1,null,3]
This difference can surprise beginners.
JSON.stringify() With Functions
Example:
const user = {
name: "Riya",
greet() {
console.log("Hello");
}
};
console.log(JSON.stringify(user));
The function property is omitted from the JSON output.
JSON represents data, not executable JavaScript functions.
JSON.stringify() With NaN and Infinity
Example:
const values = {
result: NaN,
maximum: Infinity
};
console.log(JSON.stringify(values));
Output:
{"result":null,"maximum":null}
Values such as NaN and Infinity are converted to null in JSON output.
JSON.stringify() With BigInt
This causes an error:
const value = 10n;
JSON.stringify(value);
BigInt is not directly supported by normal JSON serialization.
If you need to preserve a BigInt, convert it to a supported representation such as a string:
const value = 10n;
const json = JSON.stringify({
value: value.toString()
});
Output:
{"value":"10"}
When reading it later, remember that the stored JSON value is now a string.
Circular References Cannot Be Stringified Normally
Consider:
const user = {
name: "Riya"
};
user.self = user;
Now:
JSON.stringify(user);
throws an error because the object contains a circular reference.
The object eventually points back to itself.
Basic JSON cannot represent that structure directly.
Date Objects and JSON
A JavaScript Date object is converted to a string when stringified.
Example:
const order = {
createdAt:
new Date("2026-09-03T10:00:00Z")
};
const json = JSON.stringify(order);
console.log(json);
The date becomes an ISO-style string.
When parsed again:
const parsed = JSON.parse(json);
parsed.createdAt is a string, not automatically a Date object.
If you need a Date, convert it:
const createdAt =
new Date(parsed.createdAt);
JSON.parse() Reviver
JSON.parse() can accept a second function called a reviver.
It lets you transform values while parsing.
Example:
const json =
'{"name":"Riya","age":28}';
const user = JSON.parse(
json,
(key, value) => {
if (key === "age") {
return value + 1;
}
return value;
}
);
console.log(user.age);
Output:
29
Beginners do not need a reviver for most tasks, but it is useful to know that parsing can transform values.
JSON.stringify() Replacer Function
The second argument can also be a function.
Example:
const user = {
name: "Riya",
password: "secret"
};
const json = JSON.stringify(
user,
(key, value) => {
if (key === "password") {
return undefined;
}
return value;
}
);
console.log(json);
Output:
{"name":"Riya"}
Again, do not use frontend serialization as your main protection for sensitive information.
Convert a JavaScript Object to JSON
Start with:
const product = {
name: "Keyboard",
price: 1500,
inStock: true
};
Convert:
const json = JSON.stringify(product);
Now json is text.
This process is often called serialization.
Convert JSON to a JavaScript Object
Start with text:
const json =
'{"name":"Keyboard","price":1500}';
Convert:
const product = JSON.parse(json);
Now product is a JavaScript object.
This process is often called deserialization or parsing.
JSON.parse() vs JSON.stringify()
A simple way to remember them:
JSON.parse()
JSON text → JavaScript value
Example:
const object = JSON.parse(jsonText);
JSON.stringify()
JavaScript value → JSON text
Example:
const jsonText =
JSON.stringify(object);
Real Website Example: Save an Object in localStorage
localStorage stores string values.
You cannot directly store an object as structured object data and expect it to return unchanged.
Suppose:
const user = {
name: "Riya",
theme: "dark"
};
Convert it to JSON:
const userJson =
JSON.stringify(user);
Save it:
localStorage.setItem(
"user",
userJson
);
You can also combine the steps:
localStorage.setItem(
"user",
JSON.stringify(user)
);
Read JSON From localStorage
Retrieve the string:
const storedUser =
localStorage.getItem("user");
Convert it back:
const user =
JSON.parse(storedUser);
Now:
console.log(user.name);
Output:
Riya
Handle Missing localStorage Data
localStorage.getItem() returns null when the key does not exist.
Avoid blindly parsing data when you are not sure it exists.
Example:
const storedUser =
localStorage.getItem("user");
if (storedUser !== null) {
const user =
JSON.parse(storedUser);
console.log(user.name);
}
A useful fallback can also be:
const user = storedUser
? JSON.parse(storedUser)
: null;
Real Website Example: Save a Shopping Cart
Suppose:
const cart = [
{
id: 1,
name: "Keyboard",
quantity: 2
},
{
id: 2,
name: "Mouse",
quantity: 1
}
];
Save:
localStorage.setItem(
"cart",
JSON.stringify(cart)
);
Read later:
const storedCart =
localStorage.getItem("cart");
const cartData = storedCart
? JSON.parse(storedCart)
: [];
Now cartData is a normal JavaScript array again.
Do Not Store Sensitive Secrets in localStorage
Do not assume that JSON or localStorage protects sensitive data.
Data stored in the browser is accessible to code running in that browser context and can be exposed by security problems.
Do not store passwords or other secrets simply because you converted them to JSON.
JSON is a format, not encryption.
JSON and the Fetch API
Most web APIs return JSON.
A common pattern looks like:
fetch("/api/products")
.then((response) => response.json())
.then((data) => {
console.log(data);
});
The method:
response.json()
reads the response body and parses JSON asynchronously.
You do not normally write:
JSON.parse(response)
on the Response object itself.
You will learn this properly in the JavaScript Fetch API tutorial.
response.json() Is Not the Same as JSON.parse()
JSON.parse() works with a JSON string you already have.
Example:
const data =
JSON.parse('{"name":"Riya"}');
response.json() is a method on a Fetch API Response.
Example:
const response =
await fetch("/api/user");
const data =
await response.json();
Both eventually give you JavaScript data, but they are used in different situations.
Sending JSON to an API
A common API request converts a JavaScript object to JSON:
const user = {
name: "Riya",
email: "riya@example.com"
};
Then:
const body =
JSON.stringify(user);
A later Fetch lesson will use it like:
fetch("/api/users", {
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body:
JSON.stringify(user)
});
The server receives JSON text in the request body.
Content-Type for JSON
HTTP APIs commonly identify JSON with:
application/json
When sending JSON with fetch(), you may need:
headers: {
"Content-Type": "application/json"
}
The exact API requirements depend on the server.
Do not assume every endpoint accepts JSON.
Real Website Example: Product API Data
Imagine an API returns:
[
{
"id": 1,
"name": "Keyboard",
"price": 1500
},
{
"id": 2,
"name": "Mouse",
"price": 700
}
]
After parsing, JavaScript can loop through the array:
for (const product of products) {
console.log(
`${product.name}: ₹${product.price}`
);
}
This is why arrays and objects are so important before learning APIs.
Real Website Example: Render Parsed JSON
HTML:
<div id="product"></div>
JavaScript:
const json = `
{
"name": "Monitor",
"price": 12000
}
`;
const product =
JSON.parse(json);
const productElement =
document.querySelector("#product");
const title =
document.createElement("h2");
const price =
document.createElement("p");
title.textContent =
product.name;
price.textContent =
`₹${product.price}`;
productElement.append(
title,
price
);
This connects JSON parsing with JavaScript DOM manipulation.
Do Not Use eval() to Parse JSON
Do not parse JSON with:
eval()
Use:
JSON.parse()
eval() executes JavaScript code and creates serious security and maintainability problems when used with untrusted strings.
JSON should be parsed as data, not executed as code.
JSON and Security
JSON itself is only a data format.
Safe handling still matters.
Do not assume:
- Parsed JSON is trustworthy
- API data is safe HTML
- JSON validation replaces server validation
- Stringified data is encrypted
- JSON from localStorage is guaranteed to be valid
Treat external data as untrusted until your application validates what it needs.
When showing text in the DOM, use:
textContent
when you do not need HTML markup.
Validate the Shape of Parsed Data
Parsing valid JSON only proves the text follows JSON syntax.
It does not prove the data has the fields or types your application expects.
Example:
const json =
'{"price":"free"}';
const product =
JSON.parse(json);
The JSON is valid.
But:
product.price
is a string instead of the number your pricing code may expect.
You may need checks such as:
if (
typeof product.price === "number"
) {
console.log("Price is valid");
}
Applications should validate important external data before relying on it.
Real Website Example: Validate Parsed Product Data
const json = `
{
"name": "Keyboard",
"price": 1500
}
`;
const product =
JSON.parse(json);
if (
typeof product.name === "string" &&
typeof product.price === "number"
) {
console.log(
"Product data is usable"
);
}
This checks the expected data types after parsing.
JSON Deep Copy Trick and Its Limits
You may see this pattern:
const copy =
JSON.parse(
JSON.stringify(original)
);
It can create a deep copy for some simple JSON-compatible data.
However, it has important limitations.
It can change or lose values such as:
undefined- Functions
- Symbols
- Date objects
NaNInfinity- BigInt
- Custom class instances
- Circular references
Do not use this as a universal deep-copy method.
Modern JavaScript also provides structuredClone() for many deep-copy use cases.
You will study copying strategies later.
JSON With Special Characters
Strings can contain escaped characters.
Example:
{
"message": "He said "Hello""
}
A backslash escapes the quote inside the string.
New lines can be represented with:
Example:
{
"message": "Line 1
Line 2"
}
JSON escaping matters when JSON is written manually.
Using JSON.stringify() usually handles required escaping for you.
Do Not Build JSON Strings Manually When You Have an Object
Avoid:
const json =
'{"name":"' +
name +
'","age":' +
age +
'}';
This is easy to break when strings contain quotes or special characters.
Prefer:
const user = {
name,
age
};
const json =
JSON.stringify(user);
Let JavaScript create valid JSON text.
Common Beginner Mistakes
Thinking a JavaScript Object Is JSON
This is a JavaScript object:
const user = {
name: "Riya"
};
It becomes JSON text only after:
JSON.stringify(user);
Thinking JSON Text Is Already an Object
This is a string:
const json =
'{"name":"Riya"}';
Parse it before using object properties:
const user =
JSON.parse(json);
Using Single Quotes Inside JSON
Invalid JSON:
{
'name': 'Riya'
}
Use double quotes:
{
"name": "Riya"
}
Leaving a Trailing Comma
Invalid:
{
"name": "Riya",
}
Remove the trailing comma.
Adding Comments to JSON
Standard JSON does not allow:
// comment
or:
/* comment */
Using undefined in JSON
undefined is not a JSON value.
Use a supported value such as null when that accurately represents your data.
Forgetting JSON.parse() Can Throw
Invalid JSON causes an error.
Use try...catch when the input can be malformed.
Forgetting JSON.stringify() Returns a String
Example:
const json =
JSON.stringify({
name: "Riya"
});
console.log(typeof json);
Output:
string
Trying to JSON.stringify() BigInt Directly
This fails:
JSON.stringify(10n);
Convert BigInt to a supported representation first when needed.
Expecting Dates to Stay Date Objects
After stringify and parse, dates represented in JSON are strings unless you convert them back.
Using JSON as Encryption
This:
JSON.stringify(data)
does not hide or encrypt anything.
It only changes the representation.
Parsing an Already Parsed Object
Wrong:
const user = {
name: "Riya"
};
JSON.parse(user);
JSON.parse() expects JSON text, not a normal object.
Stringifying Before Reading Object Properties
You do not need:
JSON.stringify(product)
to access:
product.name
Use the JavaScript object directly.
Stringify it only when you need JSON text.
Using eval() for JSON
Never replace:
JSON.parse(jsonText)
with:
eval(jsonText)
for JSON parsing.
Trusting Parsed API Data Automatically
Valid JSON can still contain unexpected or malicious values.
Check the data your application relies on.
Best Practices for JSON in JavaScript
Use JSON.parse() for JSON text.
Use JSON.stringify() when you need JSON text from JavaScript data.
Do not confuse JSON with JavaScript object literals.
Use valid double-quoted JSON syntax.
Avoid manually building JSON strings.
Use try...catch when parsing data that may be malformed.
Validate important parsed values before using them.
Use textContent when displaying untrusted text from JSON.
Do not store sensitive secrets simply because the data is stringified.
Remember that JSON supports only a limited set of data types.
Do not rely on stringify-and-parse as a universal deep-copy method.
Use readable indentation with:
JSON.stringify(value, null, 2)
when debugging or creating human-readable JSON.
Beginner Exercise
Start with this JavaScript object:
const student = {
name: "Amit",
age: 20,
skills: [
"HTML",
"CSS",
"JavaScript"
]
};
Complete these tasks:
- Convert the object into JSON text.
- Print the JSON string.
- Check its type with
typeof. - Parse the JSON back into a JavaScript object.
- Print the student’s name.
- Print the second skill.
- Check whether the parsed
skillsvalue is an array.
Challenge Exercise
Create this JSON string:
const json = `
[
{
"id": 1,
"name": "Keyboard",
"price": 1500
},
{
"id": 2,
"name": "Mouse",
"price": 700
},
{
"id": 3,
"name": "Monitor",
"price": 12000
}
]
`;
Complete these tasks:
- Parse the JSON.
- Loop through every product.
- Print each product name.
- Calculate the total of all prices.
- Print only products costing more than ₹1,000.
- Convert the final array back into JSON.
Extra Challenge
Save the parsed product array in:
localStorage
using:
JSON.stringify()
Then read it back with:
JSON.parse()
Confirm that the restored value is an array.
Frequently Asked Questions
What is JSON in JavaScript?
JSON is a text format used to represent structured data. JavaScript can convert JSON text into values with JSON.parse() and convert JavaScript values into JSON text with JSON.stringify().
What does JSON stand for?
JSON stands for JavaScript Object Notation.
Is JSON the same as a JavaScript object?
No.
JSON is a text format.
A JavaScript object is a runtime JavaScript value.
They use similar syntax but follow different rules.
How do I convert JSON to a JavaScript object?
Use:
const object =
JSON.parse(jsonText);
How do I convert a JavaScript object to JSON?
Use:
const jsonText =
JSON.stringify(object);
What does JSON.parse() return?
It returns the JavaScript value represented by the JSON text.
That value may be an object, array, string, number, boolean, or null.
What does JSON.stringify() return?
It returns a string containing JSON text.
Can JSON contain arrays?
Yes.
Example:
{
"skills": [
"HTML",
"CSS",
"JavaScript"
]
}
Can JSON contain nested objects?
Yes.
JSON values can contain nested objects and arrays.
Can JSON contain undefined?
No.
undefined is not a standard JSON value.
Can JSON contain functions?
No.
JSON represents data, not executable JavaScript functions.
Can JSON contain BigInt?
Not directly with normal JSON serialization.
JSON.stringify() throws when it encounters a BigInt unless you convert it to a supported representation first.
Why does JSON.stringify() remove undefined properties?
undefined is not a JSON value, so object properties containing it are omitted during normal JSON serialization.
Why does JSON.stringify(NaN) produce null?
NaN is not a JSON number value.
Normal JSON serialization converts NaN and infinity values to null.
Can JSON store a Date?
JSON has no special Date type.
A JavaScript Date commonly becomes a string during JSON.stringify().
After parsing, you must create a new Date if you need Date behavior again.
What happens if JSON.parse() receives invalid JSON?
It throws a SyntaxError.
Use try...catch when the JSON may be malformed.
What is the difference between JSON.parse() and response.json()?
JSON.parse() parses a JSON string you already have.
response.json() reads and parses the body of a Fetch API Response asynchronously.
Can I store an object in localStorage?
localStorage stores strings.
Convert the object first:
localStorage.setItem(
"user",
JSON.stringify(user)
);
Then parse it when reading:
const user =
JSON.parse(
localStorage.getItem("user")
);
Handle missing or invalid stored data when necessary.
Is JSON secure?
JSON is only a data format.
It is not encryption, authentication, validation, or sanitization.
Should I use eval() to parse JSON?
No.
Use:
JSON.parse()
Can I deep copy an object with JSON stringify and parse?
It works for some simple JSON-compatible data, but it can lose or change unsupported values and fails with circular references.
Do not treat it as a universal deep-copy solution.
Why do APIs use JSON?
JSON is compact, widely supported, and easy for frontend and backend systems to exchange and process.
What should I learn after JSON?
Learn the JavaScript Fetch API next. Fetch lets your browser request JSON from APIs and send JSON data to servers.
Summary
JSON is a text format used to store and exchange structured data.
Valid JSON can contain:
- Strings
- Numbers
- Booleans
null- Arrays
- Objects
The two most important JavaScript JSON methods are:
JSON.parse()
and:
JSON.stringify()
Use:
JSON.parse()
for:
JSON text → JavaScript value
Use:
JSON.stringify()
for:
JavaScript value → JSON text
You also learned how to:
- Write valid JSON
- Distinguish JSON from JavaScript objects
- Parse JSON objects and arrays
- Handle invalid JSON
- Pretty-print JSON
- Understand unsupported values
- Work with dates
- Save objects in localStorage
- Restore JSON from localStorage
- Prepare JSON for API requests
- Avoid
eval() - Validate parsed external data
- Avoid common JSON mistakes
Understanding JSON prepares you for working with real web APIs.
Continue Learning JavaScript
Previous Lesson: JavaScript Form Validation Explained
Course Home: JavaScript Tutorial for Beginners
Next Lesson: JavaScript Fetch API Explained
In the next lesson, you will learn how to request JSON data with fetch(), check HTTP responses, use response.json(), send POST requests, and handle API errors.
