Learning notes of JSON must know and be able (I)

Time:2021-12-24

What is JSON

The full name of JSON is JavaScript object notation, which is a text format (data exchange format) for transferring data between different platforms. There are two common data exchange formats: XML and JSON. We mainly study JSON.

Data exchange formats are very important, and developers need to use them to realize data exchange between different systems.

JSON is based on JavaScript object literals, but it is independent of any programming language. What really matters is the representation itself, so you don’t have to learn JavaScript before learning JSON. Of course, it’s great to have a JavaScript foundation.

JSON syntax

The data structure using key value pairs in JSON is as follows:

{
    "name": "dawei",
    "age":22,
    "isMan":true
}

Names always need to be enclosed in double quotes, and multiple key value pairs are separated by commas.

Both of the following representations are wrong:

{ name: "dawei" }

This is a JavaScript object, not JSON

{ 'name': 'dawei' }

This is also a JavaScript object, because single quotation marks are allowed to replace double quotation marks in JavaScript objects.

JSON data exchange format can exist in the file system as an independent file with file extension json。 When transmitting data, the receiver needs to be informed in advance of the type of data received. At this time, the media type, also known as content type or MIME type, will be involved. The common MIME type is text / HTML, and the MIME type of JSON is application / JSON.

JSON data type

The data types in JSON include: object, string, number, Boolean, null and array.

object type

The object type in JSON is very simple. JSON itself is an object, that is, it is supported by a pair of curly braces{}List of key value pairs for the package. Objects can be nested.

Object can contain multiple key value pairs.
The key must be a string, and the value can be a valid JSON data type (string, number, object, array, Boolean or null).

{
    "person":{
        "name":"dawei",
        "age":23,
        "isBoy":true
    }
}

String type

In JSON, strings must and can only be wrapped in double quotes. In JSON, keys are of string type. In JavaScript, there is no difference between single quotation marks and double quotation marks. However, JSON is not a JavaScript object literal, it is only based on JavaScript object literals.

For the JSON parser, when a value starts with a double quote, it expects the next string text to end with another double quote. This means that if the string itself contains double quotation marks, an error may be reported. At this time, we need to use the backslash to escape the double quotation marks in the string.

{
    "promo":"He say \"Bob`s the best!\" at classroom"
}

Number type

The number type in JSON can be integer, decimal, negative or exponential.

Boolean type

Boolean values in JSON can only be in lowercase form: true or false. Any other writing method will report an error.

Null type

In JSON, using null means nothing, nonexistence, etc.

For the following example, since the object does not wear a watch, there is no watch color:

{
    "freckleCount":0,
    "fairy":true,
    "watchColor":null
}

Array type

Arrays should always be enclosed in square brackets[]Package. The values in the array are separated by commas.

These values can be any valid JSON data type. Therefore, there can be an array composed of strings, an array composed of numbers, an array composed of Boolean values, an array composed of objects, and even an array composed of arrays.

The array can also contain values of different data types:

{
    "eggCarton":["egg",null,"egg",5,"egg"]
}

This is also legal in JSON, but we should avoid using it like this. Because if we pass JSON containing arrays of different data types to a system that does not use JavaScript, we may report errors during parsing.

JSON schema

The data in JSON is transmitted to the receiver through the Internet or other networks, and the receiver will have an expectation of the data it wants to receive. The receiver will provide a document to explain the expected format and provide examples. In addition, JSON mode can also be used by the receiver for the other end of the transmitter. JSON mode is often located in the first row of data to be received to ensure that the data meets the requirements.

We collectively refer to the above practices as “consistency verification”. Here we want to verify the contents of three aspects:

  • Whether the value type is correct – you can specify that a value is a number, string, etc

  • Whether the required data is included – which data is required and which is not required can be specified

  • Whether the form of the value is what we need — you can specify the range, minimum and maximum values

JSON schema is written in JSON. A complete file in JSON schema format is as follows:

{
    "$schema":"http://json-schema.org/draft-04/schema#",
    "title":"Cat",
    "properties":{
        "name":{
            "type":"string",
            "minLength":3,
            "maxLength":20
        },
        "age":{
            "type":"number",
            "description":"You cat's age in years.",
            "minimum":0
        },
        "declawed":{
            "type":"boolean"
        },
        "description":{
             "type":"string"
        }
    },
    "required":[
        "name",
        "age",
        "declawed"
    ]
}

In this file, the first key value pair declares a schema file, the second key value pair is the title of the file, the third key value pair is the attribute that needs to be included in JSON, and the fourth key value pair specifies the attribute that must be included. In the attribute value, the attribute type, the description of the attribute and the range of values are described.

Security issues in JSON

JSON itself does not have any security problems, but there are often two security problems when using JSON in the Web: Cross Site Request Forgery and cross site script attack.

Cross-site request forgery

Cross Site Request Forgery (CSRF) is a way to attack by using the site’s trust in the user’s browser.

This trust is actually the user’s login credentials. In order to obtain the user’s credentials, hackers will send a large number of forged “message reminders” to the user when the user logs in to the site. The purpose is to let the user click it and visit the website with dangerous scripts. Once the user clicks this message to remind and visit the malicious website, the hacker can obtain the user’s sensitive information (login credentials) to attack:

<script></script>

Generally, websites with poor security awareness use the following JSON URLs to store sensitive information:

[
    {
        "username":"dawei"
    },
    {
        "phone":"555-555-555"
    }
]

The JSON format here is legal, but it is very dangerous because it is also an executable JS script. Hackers can easily save it to their own site script.

How to prevent CSRF attacks?

First, you should store the array as a value in the JSON object, so that the array will no longer be legal JavaScript and the script will not be able to load it.

{
    "info":[
        {
            "username":"dawei"
        },
        {
            "phone":"555-555-555"
        }
    ]
}

Second, the site should only allow post requests and static get requests. So hackers can’t use the URL in the script.

Injection attack

Injection attacks take advantage of the vulnerabilities of the system itself to inject malicious code into the website to attack.

Cross site scripting attack

Cross site scripting attack (XSS) is a kind of injection attack. When using JSON, common security vulnerabilities usually occur when JavaScript obtains a JSON string from the server and converts it into a JavaScript object.

In JavaScript, you can useeval()Function to do this:

var jsonString = '{"animal":"cat"}';
var myObject = eval("("+ jsonString +")");
alert(myObject.animal);

It seems that there is no problem, but if the server or the JSON sent by the server is attacked and carries malicious code, the situation will be very bad:

var jsonString = "alert('this is bad code')";
var myObject = eval("("+ jsonString +")");
alert(myObject.animal);

eval()The problem is that it will compile and execute the incoming string indiscriminately. In this way, it will give hackers an opportunity and may bring us incalculable losses.

In order to solve this problem, theJSON.parse()Method, which only parses JSON and does not execute scripts:

var jsonString = '{"animal":"cat"}';
var myObject = JSON.parse("("+ jsonString +")");
alert(myObject.animal);

To be continued