JSON Lines 是一种文本格式,适用于存储大量结构类似的嵌套数据、在协程之间传递信息等。git
例子以下:github
{"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♣"]]}
它有以下特色:web
// 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 却能够很容易地表示出来:json
{ "familyMembers": ["JuZhiyuan", "JuShouChang"] }
既然 JSON 如此灵活,那为什么还须要 JSON Lines 呢?api
考虑以下场景:一个大小为 1GB 的 JSON 文件,当咱们须要读取/写入内容时,须要读取整个文件、存储至内存并将其解析、操做,这是不可取的。app
若采用 JSON Lines 保存该文件,则操做数据时,咱们无需读取整个文件后再解析、操做,而能够根据 JSON Lines 文件中每一行便为一个 JSON 值 的特性,边读取边解析、操做。例如:在插入 JSON 值时,咱们只须要 append 值到文件中便可。编码
所以,操做 JSON Lines 文件时,只须要:code
那么如何将 JSON Lines 转换为 JSON 格式呢?下方代码为 JavaScript 示例:orm
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);