JSON Responses

A common AJAX response format would be in plain text, HTML, XML, and JSON.
JSON is the best type of response. It stands for JavaScript Object Notation.
JSON data can be formatted as an array of values, as a JavaScript object, or a combination of both.
A JSON property name must be quoted using double quotes.

Create an intranet widget that gets a list of online and offline employees from the server.

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
  if(xhr.readyState === 4 && xhr.status === 200) {
    var employees = JSON.parse(xhr.responseText);
    var statusHTML = '<ul class="bulleted">';
    for (var i=0; i<employees.length; i += 1) {
      if (employees[i].inoffice === true) {
        statusHTML += '<li class="in">';
      } else {
        statusHTML += '<li class="out">';
      }
      statusHTML += employees[i].name;
      statusHTML += '</li>';
    }
    statusHTML += '</ul>';
    document.getElementById('employeeList').innerHTML = statusHTML;
  }
};
xhr.open('GET', '../data/employees.json');
xhr.send();

 

Parsing JSON File

When a web server sends JSON-formatted data, it is actually sending a string. Therefore, before processing the JSON data, we need to use the JSON.parse() method which is a web browser’s method that turns a JSON string into a JavaScript object.
 

Writing a JSON File

In order to use JavaScript to write a JSON file to the hard drive, you need to use Node.js. The fs module in Node provides file I/O functionality.

"use strict";

let obj = {
	firstName: "Steven",
	lastName: "Hancock", 
	score: 80
};

let jsonData = JSON.stringify(obj);
let fs = require('fs');
fs.writeFile(
    "./JSON/sample.json", 
    jsonData, 
    function(err) { 
      if (err) { console.log(err); }
    }
);

 

JSONLint

JSONLint – A JSON Validator https://jsonlint.com/