Workspace
  • Study Book
  • WEB Network HTTP etc
    • Performance Optimization
    • Performance Optimization
    • HTTP/2 & SPDY
    • WebSocket
    • HTTP Header
    • Cross-Origin Resource Sharing
    • JSON, XML, other format
  • Javascript
    • Promise
    • make API call
    • Web API
    • Common JS
    • AJAX
    • Event DOM and delegation
    • ES6 new features
    • special function
    • function API
  • React
    • class component
    • Example
    • Lifting functions/ state up
    • Hot Loader
    • Testing
    • New Features
    • Hook
    • Simple code
    • Life Cycle
  • CSS
    • Horizontal & Vertical Align
    • GPU Animation
    • transform-function
    • LVHA Pseudo-classes
    • Selector
    • How To CSS
  • HTML
  • Redux
  • NodeJS
    • File System
  • express
    • express questions
    • express mongodb
  • Restful API
  • MongoDB
  • Compare
  • Test
    • Jest
  • Deploy development
  • coding question
  • DevOps
  • Webpack
  • GraphQL
Powered by GitBook
On this page
  • JSON's basic data types are:
  • Looping Through an Array
  • Looping Through an Array
  • Parsing JSON
  • JSON From the Server
  • Array as JSON
  • JSON.stringify()
  • JSON Applications
  • Sending Data
  • Receiving Data
  • JSONP​
  • HTTP GET only
  • No error handling
  • Vulnerability
  • XML
  • Storing Data
  • What is MessagePack?

Was this helpful?

  1. WEB Network HTTP etc

JSON, XML, other format

JSON's basic data types are:

  • Number: a signed decimal number that may contain a fractional part and may use exponential E notation, but cannot include non-numbers such as NaN. The format makes no distinction between integer and floating-point. JavaScript uses a double-precision floating-point format for all its numeric values, but other languages implementing JSON may encode numbers differently.

  • String: a sequence of zero or more Unicode characters. Strings are delimited with double-quotation marks and support a backslash escaping syntax.

  • Boolean: either of the values true or false

  • Array: an ordered list of zero or more values, each of which may be of any type. Arrays use square bracket notation with comma-separated elements.

  • Object: a collection of name–value pairs where the names (also called keys) are strings. Objects are intended to represent associative arrays,[7] where each key is unique within an object. Objects are delimited with curly brackets and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.

    null: an empty value, using the word null

    Whitespace is allowed and ignored around or between syntactic elements (values and punctuation, but not within a string value). Four specific characters are considered whitespace for this purpose: space, horizontal tab, line feed, and carriage return. In particular, the byte order mark must not be generated by a conforming implementation (though it may be accepted when parsing JSON). JSON does not provide syntax for comments

Looping Through an Array

access: x = myObj.cars[0];

Looping Through an Array

for (i in myObj.cars) {

x += myObj.cars[i];

}

for (i = 0; i < myObj.cars.length; i++) {

x += myObj.cars[i];

}

Parsing JSON

JavaScript function JSON.parse() to convert text into a JavaScript object:var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');

JSON From the Server

Use the XMLHttpRequest to get data from the server:

var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myObj = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myObj.name; } }; xmlhttp.open("GET", "json_demo.txt", true); xmlhttp.send();

Array as JSON

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var myArr = JSON.parse(this.responseText); document.getElementById("demo").innerHTML = myArr[0]; } }; xmlhttp.open("GET", "json_demo_array.txt", true); xmlhttp.send();

JSON.stringify()

Use the JavaScript function JSON.stringify() to convert it into a string.

var obj = { name: "John", age: 30, city: "New York" };

var myJSON = JSON.stringify(obj);

myJSON is now a string, and ready to be sent to a server:

var arr = [ "John", "Peter", "Sally", "Jane" ]; var myJSON = JSON.stringify(arr); document.getElementById("demo").innerHTML = myJSON;

JSON Applications

JSON-RPC

AJAJ

Sending Data

var myObj = {name: "John", age: 31, city: "New York"};

var myJSON = JSON.stringify(myObj);

window.location = "demo_json.php?x=" + myJSON;

Receiving Data

var myJSON = '{"name":"John", "age":31, "city":"New York"}';

var myObj = JSON.parse(myJSON);

document.getElementById("demo").innerHTML = myObj.name;

JSONP​

JSONP is a method for sending JSON data without worrying about cross-domain issues.

JSONP does not use the XMLHttpRequest object.

JSONP uses the <script> tag instead.

Use JSONP (JSON with Padding) as a means to prevent CORS requests to happen

Failed to load resource: Origin * is not allowed by Access-Control-Allow-Origin.

HTTP GET only

The JSONP way is only applicable to HTTP GET requests, no other method is supported. This is logical since the <script> tag can only make HTTP GET requests anyway. And this is precisely what we have leveraged earlier.

No error handling

Typically when working with AJAX requests we can see the error body returned by the API, however, using JSONP we either get a CORS error or we are faced with a 404 error. Either way, it's incredibly difficult to debug errors when using JSONP.

Vulnerability

JSONP exposes multiple vulnerabilities - it assumes excessive trust, it also further exposes CSRF (Cross-Site Request Forgery) vulnerabilities.

All in all, it is best not to use JSONP.

// api.js
const express = require('express');
const app = express();
const port = 3000;

const apiHandler = (request, response) => {
  response.json({ message: 'Hello World!' });
};

app.get('/api/hello', apiHandler);

app.listen(port, () => console.info(`API up on port ${port}.`));
// http-server.js
const http = require('http');
const path = require('path');
const fs = require('fs');
const port = 8080;

const httpServerHandler = (request, response) => {
  response.writeHead(200);
  response.write(fs.readFileSync(path.join(`${process.cwd()}/index.html`)));
  response.end();
};

http.createServer(httpServerHandler).listen(port);
console.log(`HTTP Server is up on port ${port}`);

Now we have two Node.js processes - one is an API server that runs on port 3000 and the HTTP server that runs on port 8080. Due to the rules behind CORS, these are considered to be two separate entities, and therefore the browser is going to block accessing resources.

XML

XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.

JSON is Like XML Because

  • Both JSON and XML are "self describing" (human readable)

  • Both JSON and XML are hierarchical (values within values)

  • Both JSON and XML can be parsed and used by lots of programming languages

  • Both JSON and XML can be fetched with an XMLHttpRequest

JSON is Unlike XML Because

  • JSON doesn't use end tag

  • JSON is shorter

  • JSON is quicker to read and write

  • JSON can use arrays

XML is much more difficult to parse than JSON. JSON is parsed into a ready-to-use JavaScript object.

For AJAX applications, JSON is faster and easier than XML:

Using XML

  • Fetch an XML document

  • Use the XML DOM to loop through the document

  • Extract values and store in variables

Using JSON

  • Fetch a JSON string

  • JSON.Parse the JSON string

Storing Data

When storing data, the data has to be a certain format, and regardless of where you choose to store it, text is always one of the legal formats.

JSON makes it possible to store JavaScript objects as text.

Storing data in local storage

// Storing data: myObj = {name: "John", age: 31, city: "New York"}; myJSON = JSON.stringify(myObj); localStorage.setItem("testJSON", myJSON); // Retrieving data: text = localStorage.getItem("testJSON"); obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.name;

What is MessagePack?

« MessagePack is an efficient binary serialization format. It lets you exchange data among multiple languages like JSON. But it’s faster and smaller ». To start using MessagePack we need to convert our application objects into MessagePack format: this process is called serialization, while the reverse process is called deserialization. The following example can help us better understand what we’re talking about. Consider this simple JSON:

JSON is the de-facto standard, especially in developing RESTful web services. JSON won against its antagonist XML (SOAP) without a battle, but it didn’t prevent the development of alternatives like Google’s Protocol Buffers, Apache Avro or MessagePack. In being thorough, we should also mention gzip JSON compression (sometimes called “JSONC"), and BSON, a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments

PreviousCross-Origin Resource SharingNextJavascript

Last updated 4 years ago

Was this helpful?