Skip to content
Charlie CedarIsle Calvert edited this page Feb 22, 2015 · 1 revision

JSON

JSON, like XML, is a text base sepecification for exchanging data. JSON is based on JavaScript. In fact, it is a subset of JavaScript. In particular, it allows you to declare simple JavaScript objects that consist of name value pairs:

{
	"firstName": "George",
	"lastName": "Washington"
}

You can also declare simple JavaScript arrays:

[a, b, c]

You can combine the two:

[
    {
        "firstName": "George",
        "lastName": "Washington"
    }, {
        "firstName": "John",
        "lastName": "Adams"
    }, {
        "firstName": "Thomas",      
        "lastName": "Jefferson"
    }
]

Reading JSON with Node

There is a library called fs (FileSystem) that is built into Node. You can load the library like this:

var fs = require('fs');

Then you can use the library to read in a file:

var json = fs.readFileSync('index.json');

The code above reads in a text file and puts the contents in the variable of type string called json. Finally, you can convert that JSON string into a real JavaScript object by writing this code:

var obj = json.parse(json);

Working with JSON {#working}

This code can go in the head section of your HTML:   <script type="textx-handlebars-template" id="par01">

{{text}}


</script>

Here is code for using the template:

function addItem(text) {  
	'use strict';  
  
	var script = \$("#par01").html(),  
	template=Handlebars.compile(script);  
  
	var result = template({  
		text: text  
	});  
  
	$("#myDiv").append(result);  
}

$.getJSON("index.json", function(data) {  
	$.each(data, function(i, president) {  
		$('#data01').append("<p>" + president.firstName 
			+ ' ' + president.lastName + "</p>");  
	});  
});

You can download jQuery from http://jquery.com

Links

Clone this wiki locally