[英]Using jq to concatenate directory of JSON files
I have a directory of about 100 JSON files, each an array of 100 simple records, that I want to concatenate into one file for inclusion as static data in an app, so I don't have to make repeated API calls to retrieve small pieces . (我一次只能下載 100 條記錄;這就是我有 100 個短文件的原因。)
這是一個示例文件,縮短為兩條記錄以便在此處顯示:
[
{
"id": 11531,
"title": "category 1",
"count": 5
},
{
"id": 11532,
"title": "category 2",
"count": 5
}
]
我的研究導致了一個有效的解決方案,但僅適用於兩個文件,每個文件有兩條記錄:
jq -s '.[0] + .[1]' file1.json file2.json > output.json
該消息來源還建議此行可以處理目錄(現在只有兩個文件):
jq -s 'reduce .[] as $item ({}; . * $item)' json_files/* > output.json
但我收到一個錯誤:
jq: error (at json_files/categories-11-20.json:0): object ({}) and array ([{"id":1153...) cannot be multiplied
我想也許問題是*
試圖乘法,所以我在那個地方嘗試了+
,但我得到了一個... cannot be added.
信息。
有沒有辦法通過 jq 做到這一點,或者有更好的工具嗎?
最簡單且完全合理的方法是使用 -s 命令行選項並add
以下行:
jq -s add json_files/*
當然,您可能希望以不同的方式指定文件列表。 指定它們的順序也很重要。
筆記:
這個Q實際上只是Use jq to concatenate JSON arrays in multiple files的變體
reduce
也可以使用,但您需要從null
或[]
而不是{}
開始。
運算符“*”(毫不奇怪)與“+”完全不同!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.