# 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](https://en.wikipedia.org/wiki/E_notation), but cannot include non-numbers such as [NaN](https://en.wikipedia.org/wiki/NaN). The format makes no distinction between integer and floating-point. JavaScript uses a [double-precision floating-point format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) for all its numeric values, but other languages implementing JSON may encode numbers differently.
* [String](https://en.wikipedia.org/wiki/String_\(computer_science\)): a sequence of zero or more [Unicode](https://en.wikipedia.org/wiki/Unicode) characters. Strings are delimited with double-quotation marks and support a backslash [escaping](https://en.wikipedia.org/wiki/Escape_character) syntax.
* [Boolean](https://en.wikipedia.org/wiki/Boolean_datatype): either of the values `true` or `false`
* [Array](https://en.wikipedia.org/wiki/Array_data_structure): an [ordered list](https://en.wikipedia.org/wiki/List_\(abstract_data_type\)) of zero or more values, each of which may be of any type. Arrays use [square bracket](https://en.wikipedia.org/wiki/Square_bracket) notation with comma-separated elements.
* [Object](https://en.wikipedia.org/wiki/Object_\(computer_science\)): a collection of [name–value pairs](https://en.wikipedia.org/wiki/Attribute%E2%80%93value_pair) where the names (also called keys) are strings. Objects are intended to represent [associative arrays](https://en.wikipedia.org/wiki/Associative_array),[\[7\]](https://en.wikipedia.org/wiki/JSON#cite_note-ecma2013-8) where each key is unique within an object. Objects are delimited with [curly brackets](https://en.wikipedia.org/wiki/Braces_\(punctuation\)#Braces) and use commas to separate each pair, while within each pair the colon ':' character separates the key or name from its value.

  [`null`](https://en.wikipedia.org/wiki/Nullable_type): an empty value, using the word `null`

  [Whitespace](https://en.wikipedia.org/wiki/Whitespace_character) 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](https://en.wikipedia.org/wiki/Space_\(punctuation\)), [horizontal tab](https://en.wikipedia.org/wiki/Horizontal_tab), [line feed](https://en.wikipedia.org/wiki/Line_feed), and [carriage return](https://en.wikipedia.org/wiki/Carriage_return). In particular, the [byte order mark](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/Comment_\(computer_programming\))

### Looping Through an Array

access: x = myObj.cars\[0];

### Looping Through an Array

for (i in myObj.cars) {&#x20;

&#x20;   x += myObj.cars\[i];&#x20;

}

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

&#x20;   x += myObj.cars\[i];&#x20;

}

## 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"};&#x20;

var myJSON = JSON.stringify(myObj);&#x20;

window\.location = "demo\_json.php?x=" + myJSON;

### Receiving Data

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

var myObj = JSON.parse(myJSON);&#x20;

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 <a href="#httpgetonly" id="httpgetonly"></a>

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 <a href="#noerrorhandling" id="noerrorhandling"></a>

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 <a href="#vulnerability" id="vulnerability"></a>

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? <a href="#what-is-messagepack" id="what-is-messagepack"></a>

« *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:

![](https://4116032991-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LgnugJ0SdX2tMAwP37V%2F-MEZIE1WPKV3ILDLvXF8%2F-MEZIfZmAG7qQ7mmk3lV%2Fimage.png?alt=media\&token=8e668be1-bdd8-4edc-8f66-c5038db2cb1e)

&#x20;[**JSON**](https://www.json.org/) is the de-facto standard, especially in developing RESTful web services. JSON won against its antagonist [XML](https://www.w3.org/XML/) (SOAP) without a battle, but it didn’t prevent the development of alternatives like [Google’s **Protocol Buffers**](https://developers.google.com/protocol-buffers/), [Apache **Avro**](https://avro.apache.org/) or [**MessagePack**](http://msgpack.org/). In being thorough, we should also mention [gzip](http://www.gzip.org/) JSON compression (sometimes called “*JSONC*"), and [BSON](http://bsonspec.org/), a bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gzqsjtu.gitbook.io/workspace/web-network-http/json-xml-other-format.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
