JSON Lines

原文 blog.shaoyaoju.org/json-lines/web

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

  1. 每一行都是完整、合法的 JSON 值;採用 \n 或 \r\n 做爲行分隔符;
  2. 採用 UTF-8 編碼;
  3. 使用 jsonl 做爲文件擴展名;建議使用 gzip 或 bzip2 壓縮並生成 .jsonl.gz 或 .jsonl.bz2 文件,以便節省空間。

對比

// 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

  1. 讀取一行值;
  2. 將值解析爲 JSON;
  3. 重複一、2步驟。 那麼如何將 JSON Lines 轉換爲 JSON 格式呢?下方代碼爲 JavaScript 示例:
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);
複製代碼

參考

  1. JSON Lines
  2. JSON Lines format: Why jsonl is better than a regular JSON for web scraping
相關文章
相關標籤/搜索