JSON learning notes - JSON you don't know

JSON learning notes - JSON you don't know

What is JSON

JSON is essentially a "data exchange format" With JSON, we can communicate with different systems Its goal is to complete data exchange JSON itself does not belong to any programming language, but a form of expression

The full name of JSON is Javascript Object Notation (Javascript object notation). Seeing this name, many people think they can learn JSON if they want to learn JavaScript. In fact, the two have nothing to do JavaScript itself is a front - end programming language JSON is a data representation method The two have little to do with each other

Difference between JSON and XML

You may have heard of XML before you heard of JSON, a data exchange format. XML itself is designed to transmit data

XML refers to eXtensible Markup Language

  • XML is designed to transmit data, not display data.
  • The data transmitted by XML is self descriptive

So why does JSON not directly use XML to transmit and save data?

I give some of my personal views, which are not necessarily right. We can discuss them together

  • I feel that JSON represents a type with fewer characters. Instead of creating a set of tags to complete the closure, I use {} to complete the data representation

  • JSON is smaller, faster, and easier to parse than XML

  • JSON is supported by many back-end languages, such as python, Java, go, PHP and node JS these languages have quite perfect libraries to parse JSON data

Corresponding xml:

<bookstore>
    <book category="CHILDREN">
        <title>Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
    </book>
    <book category="WEB">
        <title>Learning XML</title>
        <author>Erik T. Ray</author>
        <year>2003</year>
        <price>39.95</price>
    </book>
</bookstore>

The corresponding json is represented as follows:

{
    "bookstore": [
        {
            "category": "CHILDREN",
            "book": {
                "title": "Harry Potter",
                "author": "J K. Rowling",
                "year": 2005,
                "price": 29.99
            }
        },
        {
            "category": "WEB",
            "book": {
                "title": "Learning XML",
                "author": "Erik T. Ray",
                "year": 2003,
                "price": 39.95
            }
        }
    ]
}

At present, json is the data format used in data transmission between the back end and the front end of web api The older system may still transmit data in xml

What is JSON?

  • JSON refers to JavaScript Object Notation
  • JSON is a lightweight text data exchange format
  • JSON is language independent: JSON uses Javascript syntax to describe data objects, but JSON is still language and platform independent. The JSON parser and JSON library support many different programming languages. At present, many dynamic (PHP, JSP,. NET) programming languages support JSON.
  • JSON is self descriptive and easier to understand

JSON - convert to JavaScript object

The JSON text format is syntactically the same as the code that creates JavaScript objects.
Because of this similarity, JavaScript programs can use the built-in eval() function to generate native JavaScript objects with JSON data without a parser.

Basic data type of JSON

JSON has six basic data types: number, object, string, array, Boolean value and null

Array values in JSON must be legal JSON data types (string, number, object, array, Boolean or null)

JSON name / value pair or key value pair

The writing format of JSON data is: name / value pair.

The name / value pair includes the field name (in double quotes), followed by a colon:, followed by the value:

Note that the name here must be enclosed in double quotation marks, not single quotation marks

{"name" : "Rookie tutorial"}

One JSON value
JSON values can be:

  • Number (integer or floating point number)
  • String (in double quotes)
  • Logical value (true or false) (lowercase)
  • Array (in square brackets)
  • Object (in braces)
  • null

The name or key of JSON can only be string type. The string here should be enclosed in double quotes

1. JSON number

JSON numbers can be integer or floating point:

{ "age":30 }

2.JSON object

JSON objects are written in braces ({}):
An object can contain multiple name / value pairs:
Note that there is no comma in the last key value pair, and all keys must be enclosed in double quotation marks, and single quotation marks are not allowed!!!

key must be a string, and value can be a valid JSON data type (string, number, object, array, Boolean or null)

{ "name":"Rookie tutorial" , "url":"www.runoob.com" }

{ 
    "_id" : ObjectId("5912cf60d616df3117e92541"), 
    "mobile" : "11116526716", 
    "name" : "Xiao Ming", 
    "id_card_number" : "320110180510158775", 
    "created_time" : "2017-05-10 16:29:19.886", 
    "Rule_final_weight" : "0", 
    "code" : "100002", 
    "flag_specialList_c" : "0", 
    "swift_number" : "304591320170510_162919_7005", 
    "return_time" : "2017-05-10 16:29:20.011", 
    "Rule_final_decision" : "Accept", 
    "flag_rulespeciallist" : "0"
}

3.JSON array

JSON arrays are written in square brackets:
The array can contain multiple objects:

JSON arrays are written in square brackets.
Array values in JSON must be legal JSON data types (string, number, object, array, Boolean or null)

{

	"call_record": [{
			"date": "2019-05-15 14:47:00",
			"duration": "28",
			"number": "12004560761",
			"type": "INCOMING"
		},
		{
			"date": "2017-03-15 15:56:32",
			"duration": "9",
			"number": "02180341912",
			"type": "INCOMING"
		},
		{
			"date": "2017-03-15 16:33:50",
			"duration": "199",
			"number": "18011230001",
			"type": "INCOMING"
		},
		{
			"date": "2017-07-02 08:29:11",
			"duration": "0",
			"number": "12580",
			"type": "OUTGOING"
		},
		{
			"date": "2017-07-02 08:29:22",
			"duration": "40",
			"number": "10010",
			"type": "OUTGOING"
		}
	]
}

If multiple elements in the array need to be separated by commas, do not add commas after the last element The following example does not have a comma after frank

[
    "Taobao",
    "Charley",
    "frank"
]

If there is only one element in the array, you do not need to add a comma

[
    "Taobao"
]

Let's look at another example

{
	"name": "website",
	"sites": ["Google", "Runoob", "Taobao"]
}

Another example is that strings, numbers, bool values, and objects can be stored in the array, that is, any json data type can be placed in the json array, which does not necessarily need to be a data type

{
	"name": "website",
	"sites": ["Google", 12, true, false,
		{
			"name": "website"
		}
	]
}

4. JSON Boolean

JSON Boolean values can be true or false

{ "flag":true }

{ "flag":false }

5. JSON null

JSON can set null value:

{"created_time":null}

Some escape problems in JSON

Sometimes we may encounter such a situation. In JSON, value itself contains double quotation marks. We know that double quotation marks are used to wrap the content you need. If its content has double quotation marks, we don't know how to parse this string when parsing JSON

For example: the value corresponding to the following body, and the following paragraph is the wrong JSON format

{
	"title":"hahah",
	"body":" This is a sentence. "I am Frank." "
}

To ensure the correctness of JSON We can add the character \ before the double quotation mark in value to escape the double quotation mark

{
	"title":"hahah",
	"body":" This is a sentence. \"I am Frank.\" "
}

Here are some special characters that need to be escaped if necessary

\Double quote escape

\/Forward slash

\b backspace

\f page feed

\t tab

\n newline

\r carriage return

\U followed by hexadecimal characters (\ u12a3)

JSON SCHEMA

JSON SCHEMA is only used to verify the legitimacy of data transmission Ensure that the data transmission meets a certain format

When interacting data in different systems, there will be no unnecessary trouble

  • Is the data type of the value correct

    You can specify the type of value, number, string, etc

  • Does it contain the required data?

    Specify which data is needed and which is not

  • Is the form of value what I need?

    It can refer to whether the range of values is legal, max,min, etc

JSON schema ensures that the data format, type and data range meet the requirements, so as to ensure the reliability of data transmission

Verify whether the json data is legal by writing the json schema file. There are many written implementations in python language, which is recommended jsonschema This library pays more attention

josn schema step by step

Implementations

JSON of server

In the current back-end web development, we use json to transmit a lot of data interactively with the front-end

First, the structure is convenient and simple

The second back - end language itself already has good support for json

Here is an example of using the flash framework in python language

The following lines of test code can return a json response

from flask import Flask, request, jsonify


def create_app():
    ins = Flask(__name__)
    return ins


app = create_app()


@app.route('/book',methods=['GET', 'POST'])
def book():

    if request.method == 'GET':
        data = {
            'author':'frank',
            'name':'Flask tutor',
            'publish_date':'2021-12-12'

        }
        return jsonify(data)

Through jsonify, you can directly change the dictionary data type in python into a json response

JSON as configuration file

Node.js default javascript package manager: npm

npm package manager, you can use json as the configuration file, package json file Here we define the package name, version, dependency, author and other information

{
    "name": "hello world",
    "version": "1.0.0",
    "scripts": {
        "dev": "vue-cli-service serve",
        "build": "vue-cli-service build",
        "lint": "vue-cli-service lint"
    },
    "dependencies": {
        "core-js": "^3.5.0",
        "element-ui": "^2.10.1",
        "json-query": "^2.1.2"
    },
    "keywords": [
        "book",
        "frank"
    ],
    "author": "frank.chang"
}

summary

As a data format, JSON plays an important role in exchanging and transmitting data between different systems

At present, in the direction of web back-end development, almost all back-end API s use JSON to transfer data

JSON can also be used as a configuration file

Some Nosql uses JSON to store data, which is not mentioned in this article

Of course, there are many data formats, including JSON and xml No data format is perfect Whether to choose what data to use depends on the environment of the system and the cost of changing to JSON Sometimes JSON may not be the best choice Just this article has done a lot of introduction to JSON, I want you to know more about this data exchange format

Reference documents

JSON must know and know books

mdn json

runnoob json

w3school json

Online learning website runoob

Use of python module json module

Share happiness and keep moving. " 2021-07-03 10:45:21' --frank

Keywords: JSON

Added by mystrymaster on Sun, 23 Jan 2022 00:14:28 +0200