JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate.

JSON is a language-independent text format that is similar to BUT more elegant than XML and is often used as a configuration file.

JSON basic syntax specification

  1. The extension of the JSON file is.json
  2. The MIME type of the JSON text isapplication/json
  3. JSON is a collection of key/value pairs. All data is stored in a JSON object, which is opened with parentheses ({) begins with a close parenthesis (}Each key is followed by a colon (:), use a comma between key and value (.).
    • The data type of a key is a string and must be wrapped in double quotes (forgetting to double quote keys or writing double quotes as single quotes is a common mistake).
    • A value can be of any of these types: String, Number, Boolean, Object, Array, or NULL.
{
  "description": "This is a JSON object."."sites": [{"name": "Apple"."url": "www.apple.com" },
    { "name": "Google"."url": "www.google.com" },
    { "name": "Facebook"."url": "www.facebook.com"}}]Copy the code

Note that annotations cannot be used in JSON files, and attempts to add annotations will raise an error. However, comments can be added by workarounds such as:

{
  "description": "Project Profile"."version": "1.0.0"."author": "Tom"
}

{
  "======== common ========": "Generic module"."common": {
    "key1": "value1"."key2": "value2"
  },
  "========= user =========": "User module"."user": {
    "key1": "value1"."key2": "value2"}}Copy the code

JavaScript support for JSON

JSON syntax is a subset of JavaScript syntax and is a built-in feature when using JSON in JavaScript. JSON objects contain two methods: the parse() method, which parses JSON, and the Stringify () method, which converts objects into JSON strings. In addition to these two methods, the JSON object itself has no other function and cannot be called or invoked as a constructor.

JSON is widely referenced in JavaScript, for example, fetching JSON data from a Web server and converting that JSON data into a JavaScript object for use.

Compatibility: Internet Explorer 8 or later is not supported. For older browsers, use JSON2 github.com/douglascroc…

JSON.parse()

The json.parse () function is used for JSON parsing, which converts a JSON string into a JavaScript object.

Syntax: JSON. Parse (text[, reviver])

  • Text: Required, a valid JSON string.
  • Reviver: Optional, a result transformation function that will be called for each member of the object.
const jsonStr = '{ "name": "Tom", "birthday": "2020-01-01" }'

const jsObj1 = JSON.parse(jsonStr)
const jsObj2 = JSON.parse(jsonStr, (key, value) = > {
  if (key === 'birthday') {
    return new Date(value).getTime()
  } else {
    return value
  }
})

console.log(jsObj1) // {name: "Tom", birthday: "2020-01-01"}
console.log(jsObj2) // {name: "Tom", birthday: 1577836800000}
Copy the code

JavaScript’s built-in global function eval() can be used to evaluate and parse JSON, such as eval(‘(‘ + jsonStr + ‘)’), but is not recommended because it is unsafe.

JSON.stringify()

The json.stringify () function is used for JSON serialization, which converts a JavaScript object into a JSON string.

Syntax: json.stringify (value[, replacer[, space]])

  • Value: Required, JavaScript value to be converted (usually an object or array).
  • Replacer: Optional. A function or array used to transform the result.
    • If replacer is a functionJSON.stringifyThis function is called, passing in the key and value for each member. Use return values instead of original values. If this function returnsundefined, the member is excluded. The key of the root object is an empty string.
    • If the replacer is an array, only the members of that array that have key values are converted. The members are converted in the same order as the keys in the array. When the value argument is also an array, the replacer array is ignored.
  • Space: Optional, adding indentation, Spaces, and newlines to the returned JSON text to make it easier to read.
    • If space is a number, the return value text is indented by a specified number of Spaces at each level (only 10 Spaces if space is greater than 10).
    • Space can also be non-numeric, as in:\t.
const jsObj = { name: 'Tom'.birthday: '2020-01-01' }
const jsArr = ['Google'.'Runoob'.'Taobao'.'Facebook']

const jsonStr1 = JSON.stringify(jsObj) // Serialize the JS object
const jsonStr2 = JSON.stringify(jsArr) // Serialize the JS array
const jsonStr3 = JSON.stringify(jsObj, ['name'])
const jsonStr4 = JSON.stringify(jsObj, (key, value) = > {
  if (key === 'birthday') {
    return new Date(value).getTime()
  } else {
    return value
  }
}, 4)

console.log(jsonStr1) // {"name":"Tom","birthday":"2020-01-01"}
console.log(jsonStr2) // ["Google","Runoob","Taobao","Facebook"]
console.log(jsonStr3) // {"name":"Tom"}
console.log(jsonStr4)
/ / {
// "name": "Tom",
// "birthday": 1577836800000
// }
Copy the code

When we copy an object directly, we are actually copying the reference address of the object, and changing one object will change the other. We can use json.parse (json.stringify (obj)) for deep copy of objects, but this approach has some limitations, such as the inability to properly handle Date, RegExp, Error, etc.

JSON Schema

  • JSON Schema official website json-schema.org/
  • JSON Schema Store github.com/schemastore…

JSON Schema describes the data format, value set, default values, and description of JSON files. It helps editors (such as IDEA, WebStorm, and VS Code) provide intelligent prompts and verification functions. JSON Schema Store provides JSON Schema definitions for more than 300 JSON files. You can use JSON Schemas directly, or you can define your own JSON Schemas.

Here’s how to manage JSON Schemas in VS Code:

After configuring JSON schema in VSCode, you can display intelligent prompts when writing JSON:

"json.schemas": [{"fileMatch": [".prettierrc"]."url": "http://json.schemastore.org/prettierrc"}]Copy the code

Or define it internally in a JSON file (which may fail validation) :

{
  "$schema": "http://json.schemastore.org/coffeelint"."line_endings": "unix"
}
Copy the code

JSON Schema loaded successfully:

JSON schema loading failed:


JSON extension libraries

JSONC (JSON with Commits)

JSONC is a JSON superset that supports single-line and multi-line comments to improve the readability of JSON files. VS Code also uses this format in its configuration files (e.g. Settings. json, keybinding. json, launch.json, etc.).

Related library:

  • Github.com/sindresorhu…
  • Github.com/microsoft/n…
  • github.com/onury/jsonc
{
    // comment
    "data": /* comment */ "value"
}
Copy the code

JSON5

github.com/json5/json5

JSON5 is a superset of JSON that brings JSON syntax closer to JavaScript syntax. The following functions are mainly extended:

  • Single-line and multi-line comments are supported.
  • Key names (names) do not need to be enclosed in double quotes.
  • A string can now be quoted using single quotes.
  • Strings can contain character escapes, and newlines can be escaped to span multiple lines.
  • Objects and arrays support trailing comma.

Example:

{
  // comments
  unquoted: 'and you can quote me on that',
  singleQuotes: 'I can use "double quotes" here',
  lineBreaks: "Look, Mom! \
No \\n's!",
  hexadecimal: 0xdecaf,
  leadingDecimalPoint: 8675309.,
  andTrailing: 8675309.,
  positiveSign: +1,
  trailingComma: 'in objects',
  andIn: ['arrays',],
  "backwardsCompatible": "with JSON",}Copy the code

How to use it?

The JSON5 API is compatible with the standard JSON API and also provides both parse() and stringify() methods.

Browsers:

<script src="Https://unpkg.com/json5@ ^ 2.0.0 / dist/index. Min. Js." "></script>
Copy the code

Node. Js:

npm install json5
Copy the code
const fs = require('fs')
const path = require('path')
const JSON5 = require('json5')

const filePath = path.join(__dirname, '.. /assets/test.json5')
const content = fs.readFileSync(filePath, 'utf-8')

JSON5.parse(JSON5.stringify(content))
Copy the code

Also, it is recommended to install the VS Code plug-in JSON5 Syntax, which provides syntax highlighting support for.json5 files.

Hjson

github.com/hjson/hjson

Hjson is a syntax extension of JSON that supports the following features:

  • Support the annotation
  • Support for multiple lines of text
  • Trailing commas are supported and optional
  • Key names can be without quotation marks
  • The key value is a string without quotes

Related library:

  • Hjson – js github.com/hjson/hjson…
{
  // use #, // or /**/ comments,
  // omit quotes for keys
  key: 1
  // omit quotes for strings
  contains: everything on this line
  // omit commas at the end of a line
  cool: {
    foo: 1
    bar: 2
  }
  // allow trailing commas
  list: [
    1.2,]// and use multiline strings
  realist:
    '''
    My half empty glass,
    I will fill your empty half.
    Now you are half full.
    '''
}
Copy the code

Profile solution

A configuration file is a very basic file format that does not need to be as complex as other formats such as data file formats (such as SQLite), document file formats (such as Markdown), programming language formats (such as JavaScript), or even binary file formats (such as PNG).

The basic requirement of configuration files is to be easy to read, write, and parse, but there has not been a good enough common file format for such a simple requirement for a long time.

JSON

JSON (.json) is a very friendly data transfer format that is used heavily in front-end projects, such as package.json used by NPM and YARN.

JSON does not support comments, multi-line text, or trailing commas. You can use the JSON extension library JSON5 or JSONC if necessary.

{
  "description": "This is an example."."env": {
    "node": false."browser": true
  },
  "sites": [{"name": "Apple"."url": "www.apple.com" },
    { "name": "Google"."url": "www.google.com" },
    { "name": "Facebook"."url": "www.facebook.com"}}]Copy the code

XML

XML (.xml) is a common configuration file format. It is easy to read and parse. It supports nested structures and arrays. It can be used by most programming languages and is used heavily in Java Spring projects.

XML is less elegant than JSON, values need to be wrapped directly in the start tag and end tag, and the document size is larger. JSON is faster to read and write and can be used directly in JS, while XML needs to be parsed using an XML parser.


      
<description>This is an example.</description>
<env>
    <node>false</node>
    <browser>true</browser>
</env>
<sites>
    <name>Apple</name>
    <url>www.apple.com</url>
</sites>
<sites>
    <name>Google</name>
    <url>www.google.com</url>
</sites>
<sites>
    <name>Facebook</name>
    <url>www.facebook.com</url>
</sites>
Copy the code

YAML

github.com/yaml/yaml

YAML (.yML) is a “modern” configuration file format that uses a strict indentation syntax to indicate hierarchy, supports annotations, supports data structures such as objects and arrays, and also supports reference files. The main disadvantage of YAML is that the specification is complex and there can be inconsistencies between different implementations.

YAML configuration files are often encountered in CI/CD projects (Travis CI, Circle CI, Docker Compose, etc.).

# This is a TAML document
description: This is an example.
env:
  node: false
  browser: true
sites:
  - name: Apple
    url: www.apple.com
  - name: Google
    url: www.google.com
  - name: Facebook
    url: www.facebook.com
Copy the code

Related library:

  • YAML github.com/eemeli/yaml
  • JS – YAML github.com/nodeca/js-y…

TOML

  • Making github.com/toml-lang/t…
  • IO /cn/v1.0.0-r…

TOML (.toml) is also a “modern” configuration file format that is easy to read and parse into data structures in multiple languages.

Compared to JSON, TOML supports annotations; TOML is more compact than YAML.

The Gitlab Runner configuration file uses the YAML format.

# This is a TOML document

title = "TOML Example"

[owner]
name = "Tom Preston-Werner"
dob = 1979-05-27T07:32:00-08:00

[database]
enabled = true
ports = [ 8001.8001.8002 ]
data= [["delta"."phi"], [3.14]]temp_targets = { cpu = 79.5, case = 72.0 }

[servers]

[servers.alpha]
ip = "10.0.0.1"
role = "frontend"

[servers.beta]
ip = "10.0.0.2"
role = "backend"
Copy the code

How to use it?

# https://github.com/BinaryMuse/toml-node
npm install toml
Copy the code
const fs = require('fs')
const path = require('path')
const toml = require('toml')

const filePath = path.join(__dirname, '.. /assets/test.toml')
const content = fs.readFileSync(filePath, 'utf-8')

toml.parse(content)
Copy the code

It is also recommended to install the VS Code plug-in Better TOML, which provides syntax highlighting support for.toml files.

HOCON

Github.com/lightbend/c…

HOCON (Human-Optimized Config Object Notation) is a flexible and easy-to-use configuration file format that supports reuse and inheritance, and is often used in Nginx, Java, Scala, and other projects. The file extension is.conf.

jdbc { diver = "com.mysql.jdbc.Driver" url = "jdbc:mysql://host:3306/database? useUnicode=true&characterEncoding=UTF-8" username = "root" password = "1234" }Copy the code

properties

Properties (.properties) is a very simple configuration file format used primarily in Java-related technologies to store configurable parameters of an application.

Each argument is stored as a “key-value pair,” typically storing a single argument per row.

jdbc_diver="com.mysql.jdbc.Driver"
jdbc_url=jdbc:mysql://localhost:3306/test
jdbc_username=root
jdbc_password=1234
Copy the code

INI

INI (.ini) is a very primitive configuration file format that is common in Windows operating systems.

It is suitable for very simple configurations and can only handle one layer of nesting at most, but when you need multiple layers of nesting, or when you need arrays, it is not enough.

; Simplest structure

a = a;
b = b; The values following the equals sign are strings (semicolons at the end of sentences are not required; It's followed by comments.)

; A slightly more complex single-layer nested structure

[c]
x = c.x
y = c.y

[d]
x = d.x
y = d.y
Copy the code

Some useful online tools

  • JSON formatting, compression, validation, JSON interconversion c.runoob.com/front-end/5…
  • JSON – www.bejson.com/xml2json/ XML transfers
  • JSON – www.bejson.com/validators/ YAML transfers…
  • JSON formatting tool.css-js.com/jsonformat….

The resources

  1. JSON www.json.org/json-zh.htm…
  2. JSON rookie tutorial tutorial | www.runoob.com/json/json-t…
  3. JSON – JavaScript | MDN developer.mozilla.org/zh-CN/docs/…
  4. YAML language tutorial – nguyen other blog www.ruanyifeng.com/blog/2016/0…