JSON.parse() is a JavaScript method used to convert a valid JSON string into a JavaScript object or value. It is essential when working with data received from APIs, stored in localStorage, or loaded from JSON files.
Key Points:
Syntax:
JSON.parse(text[, reviver])text: The JSON string to parse.reviver(optional): A function that transforms the parsed values before returning them.
Returns: A JavaScript object, array, string, number, boolean, or
null, depending on the JSON content.Throws:
SyntaxErrorif the input string is not valid JSON (e.g., invalid syntax, trailing commas, single quotes instead of double quotes).Use Cases:
Parsing API responses:
fetch('/api/data').then(res => res.json()).then(data => console.log(JSON.parse(data)))Retrieving stored data:
const user = JSON.parse(localStorage.getItem('user'))Converting JSON strings to usable JavaScript objects.
Example:
const jsonString = '{"name": "Alice", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Output: "Alice"Advanced Use: Reviver Function
The reviver function allows you to modify values during parsing:
const json = '{"date": "2025-01-01"}';
const obj = JSON.parse(json, (key, value) => {
if (key === 'date') return new Date(value);
return value;
});
console.log(obj.date); // Output: Date object⚠️ Note: Always validate JSON input before parsing to avoid runtime errors. Use
try...catchfor robust error handling.
A Javascript object is a data type in Javascript - it's have property and value pair as you define in your first example.
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now What is Json : A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other)
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
so it's is a String With json Format.
and at last JSON.parse() Returns the Object corresponding to the given JSON text.
How does JSON.parse() work?
Parse json
Is JSON.parse() safe? Or Am I leaving myself exposed to injection attacks?
parse JSON manually
Videos
A Javascript object is a data type in Javascript - it's have property and value pair as you define in your first example.
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now What is Json : A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other)
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
so it's is a String With json Format.
and at last JSON.parse() Returns the Object corresponding to the given JSON text.
Here is my explanation with a jsfiddle.
//this is already a valid javascript object
//no need for you to use JSON.parse()
var obj1 = {"name":"abcd", "details":"1234"};
console.log(obj1);
//assume you want to pass a json* in your code with an ajax request
//you will receive a string formatted like a javascript object
var str1 = '{"name":"abcd", "details":"1234"}';
console.log(str1);
//in your code you probably want to treat it as an object
//so in order to do so you will use JSON.parse(), which will
//parse the string into a javascript object
var obj2 = JSON.parse(str1);
console.log(obj2);
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
I'm building a js server app and for convenience I'm using JSON.parse() to convert user input into a nested array of strings. For example "a, b, (c, d)" becomes ["a", "b", ["c", "d"]].
It is safe to use JSON.parse() for this use case?
var json = Function("return {\
foo: {\
bar: 'something',\
baz: {\
jack: 'other',\
jill: 5\
},\
bob: {\
bill: 'hello',\
bilbo: 11,\
baggins: {\
fizz: 'buzz'\
}\
}\
}\
}")(); // object
Building upon phihag's answer, I just made this up. It might be a start for you.
It does not support:
- Spaces outside key/value
- Any of
,{}:"as key/value - Arrays
- No error handling
- (Probably more - I haven't tested this extensively)
The code:
var json = '{"a":{"b":"test"},"c":123,"d":{"nested":{"key":null}}}';
var split = function(str, delimiter, func) {
var res = [];
var before = 0;
for(var i = 0; i < str.length; i++) {
if(str[i] === delimiter) {
if(func(str, i) === true) {
res.push(str.substring(before, i));
before = i + 1;
}
}
}
res.push(str.substring(before));
return res;
};
var amountbefore = function(str, pos, character) {
var amount = 0;
for(var i = 0; i < pos; i++) {
if(str[i] === character) {
amount++;
}
}
return amount;
};
var parse = function(obj) {
var stripped = obj.slice(1, -1);
var splitted = split(stripped, ",", function(str, i) {
return amountbefore(str, i, "{") === amountbefore(str, i, "}");
});
var res = {};
if(stripped === "") return res;
for(var i = 0; i < splitted.length; i++) {
var spl = split(splitted[i], ":", function(str, i) {
return amountbefore(str, i, "{") === amountbefore(str, i, "}")
});
var val;
if(spl[1][0] === "n") val = null;
if(/^\d/.test(spl[1][0])) val = spl[1] - 0;
if(spl[1][0] === "\"") val = spl[1].slice(1, -1);
if(spl[1][0] === "{") val = parse(spl[1]);
res[spl[0].slice(1, -1)] = val;
}
return res;
};
parse(json); // parses the JSON string