Learn JSON Basics Series
This is part two in an instructional two part series of blog posts about JSON.

JSON objects vs JavaScript objects

Read up on our Introduction to JSON post if you’re unfamiliar with the basics this data text tool. The following is Valid JSON within a .js file.

var validJSON = '{\
		"title":"Hello world!",\
		"content":"Welcome to JSON!"\
	oneLineJSON = '{ "id":1, "title":"Hello world!", "content":"Welcome to JSON!" }';

console.log( validJSON );
console.log( oneLineJSON );

If you want to write a JSON variable on multiple lines and make it easier to read you have to use a backslash ‘\’ to indicate a new line. Or write the variable on one line. Outputting these JSON object properties won’t work until you convert the object into a JavaScript object.

Convert JSON object into a JavaScript object

JavaScript has a helpful native object called JSON that has two methods built in: JSON.parse() & JSON.stringify(). JSON.parse() allows us to take a JSON object and parse it into a JavaScript object. JSON.stringify() takes a JavaScript object and convert it into a JSON string. These two functions will enable us to either bring a JSON object into JavaScript or generate a JSON object pushing it out of our JavaScript. Lets take a look at both of these in action.

console.log( JSON );

Notice that when you log out JSON into the console you can see it has the parse & stringify() functions.

var oneLineJSON = '{ "id":1, "title":"Hello world!", "content":"Welcome to JSON!" }',

parsedJSON = JSON.parse( oneLineJSON );
// Output the title property
console.log( parsedJSON.title );

We converted the JSON formatted string variable oneLineJSON into a JavaScript object using the JSON.parse() method and then logged the title property to the console.

var postObj = {
		"title":"Hello world!",
		"content":"Welcome to JSON!"

JSONObj = JSON.stringify( postObj );
console.log( JSONObj );

We created the JavaScript object postObj and the converted it into a JSON formatted string and stored it in the variable JSONObj.

JSON and JavaScript Review

  • Can convert JavaScript objects and and from JSON
  • JSON object, JSON.parse, JSON.stringify
  • More JSON knowledge