Processing JSON - jpjohnsonjr/learning-notes GitHub Wiki

About JSON

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.

JSON Syntax Rules

  • 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

JSON Example

{ 
  "firstName": "Yaakov",
  "lastName": "Chaikin",
  "likesChineseFood": false,
  "numberOfDisplays": 2
}

Common Misconception

  • 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

Converting JSON to String and Back to JSON

This converts from JSON string to object:

var obj = JSON.parse(jsonString);

This converts from object to JSON string:

var str = JSON.stringify(obj);

Example

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>"
    });
});
⚠️ **GitHub.com Fallback** ⚠️