JSON Lines 是一种文本格式,适用于存储大量结构类似的嵌套数据、在协程之间传递信息等。json
例子以下:api
{"name": "Gilbert", "wins": [["straight", "7♣"], ["one pair", "10♥"]]}
{"name": "Alexa", "wins": [["two pair", "4♠"], ["two pair", "9♠"]]}
{"name": "May", "wins": []}
{"name": "Deloise", "wins": [["three of a kind", "5♣"]]}
复制代码
它有以下特色:bash
// CSV
id,father,mother,children
1,Mark,Charlotte,1
2,John,Ann,3
3,Bob,Monika,2
复制代码
// JSON
[
{
"id": 1,
"father": "Mark",
"mother": "Charlotte",
"children": 1
},
{
"id": 2,
"father": "John",
"mother": "Ann",
"children": 3
},
{
"id": 3,
"father": "Bob",
"mother": "Monika",
"children": 2
}
]
复制代码
对于一样的数据内容,CSV 比 JSON 更简洁,但却不易读。此外,CSV 没法表示嵌套数据,例如一个家庭下所有成员的名字,但 JSON 却能够很容易地表示出来:app
{
"familyMembers": ["JuZhiyuan", "JuShouChang"]
}
复制代码
既然 JSON 如此灵活,那为什么还须要 JSON Lines 呢?ui
考虑以下场景:一个大小为 1GB 的 JSON 文件,当咱们须要读取/写入内容时,须要读取整个文件、存储至内存并将其解析、操做,这是不可取的。编码
若采用 JSON Lines 保存该文件,则操做数据时,咱们无需读取整个文件后再解析、操做,而能够根据 JSON Lines 文件中每一行便为一个 JSON 值 的特性,边读取边解析、操做。例如:在插入 JSON 值时,咱们只须要 append 值到文件中便可。spa
所以,操做 JSON Lines 文件时,只须要:code
const jsonLinesString = `{"name": "Gilbert", "wins": [["straight", "7♣"], ["one pair", "10♥"]]} {"name": "Alexa", "wins": [["two pair", "4♠"], ["two pair", "9♠"]]} {"name": "May", "wins": []} {"name": "Deloise", "wins": [["three of a kind", "5♣"]]}`;
const jsonLines = jsonLinesString.split(/\n/);
const jsonString = "[" + jsonLines.join(",") + "]";
const jsonValue = JSON.parse(jsonString);
console.log(jsonValue);
复制代码