json - 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.
解决方案
这是一个使用 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)
推荐阅读
- python - 如何在 if 语句中向用户提出多个问题?
- java - 如何使用分页进行动态 Spring (Boot) JPA 查询?
- javascript - 如何使用反应返回路由内的组件(包括布尔方法、映射等)
- powershell - PowerShell浮点精度 - 提取实数的小数部分
- class - 将 BEM 类添加到 html TAG
- windows - Launch a UWP app automatically after installing from an MDM server
- mysql - SHOW GRANTS TO user ''usename' with filter on role (SNOWFLAKE)
- java - 在 AndroidStudio (Java) 中用 _ 替换“”
- python - 数据提取功能未返回应有的内容
- carousel - 与延迟加载同步的光滑滑块