Standard JSON format
JSON in js
JavaScript Object Notation (JSON) is a data interchange format. Although not strictly a subset, JSON is very close to a subset of JavaScript syntax.
js to convert JSON
JSON is closer to the native syntax supported by js, so it also has a built-in parsing API:
JSON.stringify
This method converts a JavaScript object or value to a JSON string, optionally replacing the value if a replacer function is specified, or optionally containing only the properties specified by the array if the specified replacer is an array.
The second parameter is often used to delete, replace:
function replacer(key, value) {
if (typeof value === "string") {
return undefined;
}
return value;
}
var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
var jsonString = JSON.stringify(foo, replacer);
// {"week":45,"month":7} 打印结果 类似于 去除了value 是字符串的类型
If the second argument is an array:
var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};
JSON.stringify(foo, ['week', 'month']);
// '{"week":45,"month":7}' 他将只保留这两数组对应的结果
The third parameter is often used to format json:
JSON.stringify({ a: 2 }, null, " ");
// 打印结果: '{\n "a": 2\n}'
// 或者这样:
JSON.stringify({ a: 2 }, null, 2);
JSON.parse
Methods are used to parse a JSON string and construct a JavaScript value or object described by the string. An optional reviver function is provided to perform transformations (operations) on the resulting object before returning.
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
JSON.parse
Parsing often reports errors, so we also need try...catch
to wrap it
It should be noted that: JSON.parse()
comma is not allowed at the end <br>Example: JSON.parse('{"foo" : 1, }');
other options
If you want to parse into json objects in JS, you can also use another hack solution:
var a = '{"foo" : 1, }'
eval(`(${a})`)
// {foo: 1}
It can be seen that its conversion is very loose, and even he supports, single quotes and no quotes
In fact, he uses the parsing ability of js, but the use of eval also has hidden dangers (mainly in terms of performance and security)
Related JSON Libraries
Here we will introduce some json related libraries that may be used
The json5 specification supports more than ordinary json and has better compatibility. It can be said to be its superset
JSON-js
Used to be compatible with ie8, similar to the official JSON API mock, which should not be commonly used now
parse-json
When parsing json, it will provide more useful errors, this library is more useful when building a basic environment
It can also play a huge role in certain business scenarios (custom fields, custom forms, etc.)
Allows to use comments in json, delete when parsing, in configuration files, or in base libraries
JSONStream
A parsing library that can parse json according to some configuration
Manipulate JSON in node
In node, because you have to manipulate files and convert json, it is very troublesome. Here I will use this library:
It is also very useful when reading configuration files
Other formats
Now that we have talked about json, we also need to understand other formats, as well as their advantages and disadvantages
BSON
JSON serializes objects into strings, and BSON serializes objects into binary.
Because it is serialized in binary, it is better than JSON in terms of time (speed of serialization and deserialization) and space (volume after serialization). The disadvantage is that binary is not readable.He also supports many data formats
{"BSON": ["awesome", 5.05, 1986]}
will be converted to:
\x31\x00\x00\x00
\x04BSON\x00
\x26\x00\x00\x00
\x02\x30\x00\x08\x00\x00\x00awesome\x00
\x01\x31\x00\x33\x33\x33\x33\x33\x33\x14\x40
\x10\x32\x00\xc2\x07\x00\x00
\x00
\x00
CSV
Its files store tabular data (numbers and text) in plain text. Plain text means that the file is a sequence of characters without data that must be interpreted like binary numbers. CSV files consist of any number of records separated by some kind of newline character;
Passenger,Id,Survived,Pclass,Name,Sex.Age
1,0,3 Braund, Mr. Owen Harris ,male, 22
2,1,1 Cumings, Mrs. John Bradley (Florence Briggs Thayer), female,38
Looks like a compact version of the table format
papaparse : This library can use js to parse csv format
YAML
Has parsers available for almost all web programming languages. It also has some extra features like circular references, soft wrapping, multi-row keys, type conversion labels, binary data, object merging, and set mapping. It's very readable and writable, and is a superset of JSON, so you can use fully qualified JSON syntax in YAML and everything will work. You hardly need quotes, it can interpret most basic data types (strings, integers, floats, booleans, etc.).
books:
- id: bk102
author: Crockford, Douglas
title: 'JavaScript: The Good Parts'
genre: Computer
Parse YAML in js:
XML
The XML language is very flexible and easy to write, but it has the disadvantage of being verbose, hard for humans to read, very hard for computers to read, and has a lot of syntax that isn't entirely necessary to convey information.
<book id="bk101">
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
Parsing library: htmlparser2
TOML
Allows deeply nested data structures to be defined in a fairly quick and concise manner. The syntax is a bit awkward compared to JSON, more like an ini file. It's not bad syntax, but it takes some getting used to.
[a.b.c]
d = 'Hello'
e = 'World'
With TOML, you can be sure to save a lot of time and file length. Few systems use it or something very similar for configuration, which is its biggest drawback. There simply aren't many languages or libraries that can be used to interpret TOML.
Toml currently only supports node
Summarize
At present, it seems that json is a good exchange, and the format for transmitting information has many shortcomings (of course, it can also be solved by some libraries)
But personally, YAML is a more popular format with room for future development. I hope you can learn it when you have time.
Reference documentation:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。