Processing JSON - jpjohnsonjr/learning-notes GitHub Wiki
JSON stands for JavaScript Object Notation. It is used frequently when passing data from the browser to the server. It's a "lightweight data-interchange format" -- simple textual representation of data. Billed on the JSON site as easy for humans to read and write, and easy for machines to parse and generate.
Like XML, independent of any programming language.
- Subset of Javascript object literal syntax, but:
- Property names must be in double quotes
- String values must be in double quotes
- Syntax for everything else is exactly like for object literal
{
"firstName": "Yaakov",
"lastName": "Chaikin",
"likesChineseFood": false,
"numberOfDisplays": 2
}
- JSON is NOT a Javascript Object Literal
- JSON is just a string
- The syntax of JSON is based on object literal
- Need to convert JSON into a JS object
This converts from JSON string to object:
var obj = JSON.parse(jsonString);
This converts from object to JSON string:
var str = JSON.stringify(obj);
In original ajax-utils.js file, added following arguments to ajaxUtils.sendGetRequest and handleResponse function: isJsonResponse.
In the section of script.js that calls the server to get the name, we have this:
$ajaxUtils
.sendGetRequest("/data/name.json",
function (res) {
var message =
res.firstName + " " + res.lastName
if (res.likesChineseFood) {
message += " likes Chinese food";
}
else {
message += " doesn't like Chinese food"
message += " and uses ";
message += res.numberOfDisplays;
message += " displays for coding.";
document.querySelector("#content")
.innerHTML = "<h2>" + message + "</h2>"
});
});