首页 > 解决方案 > How to merge multiple Json files in folder in certain order

问题描述

I have several JSON files in a folder and I want to combine them in a single one following certain order given in order.json

I´ve tested the code below that merges all the files but in alphabetical order based on file name.

jq -s . *.json > Merged.json

This is the file Shoes.json

{ "document": { "product": "Shoes", "info": [ { "day": "1", "month": "1", "entry": "Some text about Shoes for day 1 and month 1", "code": "AJKD" }, { "day": "2", "month": "1", "entry": "Some text about Shoes for day 2 and month 1", "code": "KKGIR" } ] } }

This is the file Watches.json

{ "document": { "product": "Watches",   "info": [ { "day": "2", "month": "3",   "entry": "Some text about Watches for day 2 and month 3",   "code": "PEWQ" }    ] }     }

This is the file Accesories.json

{ "document": { "product": "Accesories",    "info": [ { "day": "7", "month": "2",   "entry": "Some text about Accesories for day 7 and month 2",    "code": "UYAAC" }   ] }     }

This is the file that gives the order I want to get in output order.json

{  
   "order":{  
      "product 1":"Watches",
      "product 2":"Accesories",
      "product 3":"Shoes"
   }
}

And the output file I´d like to get would be like this Merged.json:

{  
   "document":[  
      {  
         "product":"Watches",
         "info":[  
            {  
               "day":"2",
               "month":"3",
               "entry":"Some text about Watches for day 2 and month 3",
               "code":"PEWQ"
            }
         ]
      },
      {  
         "product":"Accesories",
         "info":[  
            {  
               "day":"7",
               "month":"2",
               "entry":"Some text about Accesories for day 7 and month 2",
               "code":"UYAAC"
            }
         ]
      },
      {  
         "product":"Shoes",
         "info":[  
            {  
               "day":"1",
               "month":"1",
               "entry":"Some text about Shoes for day 1 and month 1",
               "code":"AJKD"
            },
            {  
               "day":"2",
               "month":"1",
               "entry":"Some text about Shoes for day 2 and month 1",
               "code":"KKGIR"
            }
         ]
      }
   ]
}

Maybe someone could help me with this case.

Any help would be very appreciated.

标签: jsonmergejq

解决方案


这是一个使用 order.json 来确定 jq 将读取哪些文件的解决方案:

jq -n '{documents: [inputs.document]}' $(jq -r '.order[] + ".json"' order.json)

上面举例说明的方法有很多优点,但是上面的行做了各种可能不成立的假设。例如,它假定任何文件名中都没有空格。

强大的文件名处理

以下假设具有 bash-ful 功能:

mapfile -t args < <(jq -r '.order[] + ".json"' order.json)
jq -n '{documents: [inputs.document]}' "${args[@]}"

如果您的 bash 没有mapfile,您可以按如下方式设置 bash 变量:

args=()
while read -r f; do 
  args+=("$f")
done < <(jq -r '.order[] + ".json"' order.json)

推荐阅读