JSON.parse() and JSON.stringify
How to use JSON.parse() and JSON.stringify() by EasyProgramming.net
by dshilkret
HTML
<!-- JavaScript Objects - JSON.parse() & JSON.stringify() #43 -->
<p>
Welcome to the 43rd Easy JavaScript tutorial, part of <a href="http://www.easyprogramming.net">EasyProgramming.net</a>. We've learned a lot about JSON and custom objects in JavaScript. Let's keep going and learn about <code>JSON.parse()</code> and <code>JSON.stringify()</code>!
</p>
<p>
When you send data to or receive data from a web server, the data is always in a string format. But there are ways to send entire objects back. You can send it all as a string with <code>JSON.stringify()</code> and use <code>JSON.parse()</code> to parse it back into JSON on your script.
</p>
<p>
One thing to note is when you're using JSON.parse(), the formatting of the string MUST be in JSON format, otherwise, you will get a syntax error. You cannot parse string that doesn't look like JSON. Let's take a look!
</p>
<h2>
Syntax of <code>JSON.stringify()</code>:</h2>
<p>
<code><pre>
var obj = {
name: "Nazmus",
city: "Boston"
};
JSON.stringify(obj); //outputs the object as a long string
</pre>
</code>
</p>
<h2>
Syntax of <code>JSON.parse()</code>:</h2>
<p>
<code><pre>
var str = '{name: "Nazmus",city: "Boston"}';
JSON.parse(str); //outputs object version of str
</pre>
</code>
</p>
<p>
<h2>
Let's practice:</h2>
<span id="output"></span>
<br /><br />
CSS
console.log(JSON.stringify(restaurant, function replacer(key, value){
if(key == 'city'){ return undefined};
return value;
}));
JavaScript
var person = {
name: 'Nazmus',
city: 'Boston',
state: 'Massachusetts',
website: 'EasyProgramming.net',
language: 'JavaScript',
job: 'Developer',
hair: 'Black',
eyes: 'Brown',
hands: 'Two',
}
console.log(JSON.stringify(person, function replacer(key, value){
if(key !== 'city'){ return "THIS IS not A CITY"};
return value;
}));
var output = document.getElementById("output");
output.innerHTML += JSON.stringify(person) + '<br />';
var str = '{"name":"Nazmus","city":"Boston","state":"Massachusetts","website":"EasyProgramming.net","language":"JavaScript","job":"Developer","hair":"Black","eyes":"Brown","hands":"Two"}';
var obj = JSON.parse(str);
for(p in obj){
output.innerHTML += obj[p] + '<br />';
}