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);