簡體   English   中英

在 Bash 或 Fish shell 中使用 JQ 拆分/分塊 JSON 文件?

[英]Splitting / chunking JSON files with JQ in Bash or Fish shell?

我一直在使用美妙的JQ 庫來解析和提取 JSON 數據以方便重新導入。 我能夠很容易地提取一個范圍,但我不確定如何在腳本中循環並檢測文件的結尾,最好是在 bash 或 fish shell 腳本中。

給定一個包裹在“結果”字典中的 JSON 文件,我如何檢測文件的結尾?

從測試中,我可以看到我將得到一個嵌套在我想要的結構中的空數組,但是如何檢測文件結束條件?:

jq '{ "results": .results[0:500] }' Foo.json > 0000-0500/Foo.json

謝謝!

我建議使用 jq 將數組拆分為您想要的 JSON 對象流(每行一個),然后使用其他工具(例如 awk)來填充文件。 以下是第一部分的完成方式:

def splitup(n):
  def _split:
    if length == 0 then empty
    else .[0:n], (.[n:] | _split)
    end;
  if n == 0 then empty elif n > 0 then _split else reverse|splitup(-n) end;

# For the sake of illustration:
def data: { results: [range(0,20)]};

data | .results | {results: splitup(5) }

調用:

$ jq -nc -f splitup.jq
{"results":[0,1,2,3,4]}
{"results":[5,6,7,8,9]}
{"results":[10,11,12,13,14]}
{"results":[15,16,17,18,19]}

對於第二部分,您可以(例如)將 jq 輸出通過管道傳輸到:

  awk '{ file="file."++n; print > file; close(file); }'

您可能感興趣的一個變體讓 jq 過濾器在交替行上同時發出文件名和 JSON; awk 腳本也會讀取文件名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM