如何以一定顺序合并文件夹中的多个Json文件

时间:2019-06-07 20:18:06

标签: json merge jq

我在一个文件夹中有几个JSON文件,我想按照order.json中给出的特定顺序将它们合并为一个文件。

我已经测试了下面的代码,该代码合并所有文件,但根据文件名按字母顺序排列。

jq -s . *.json > Merged.json

这是文件 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" } ] } }

这是文件 Watches.json

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

这是文件 Accesories.json

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

这是在输出 order.json

中给出我要获取订单的文件
{  
   "order":{  
      "product 1":"Watches",
      "product 2":"Accesories",
      "product 3":"Shoes"
   }
}

我想要获取的输出文件将如下所示: 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"
            }
         ]
      }
   ]
}

也许有人可以帮助我解决这个问题。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

以下解决方案的优点是不需要任何特定于Shell的功能,而只需一次调用jq。它假定您希望能够处理order.json确定的任意多个文件。除其他假设外,在pwd中,我们可以使用模式[A-Z]*.json选择相关的“文档”。

jq -n --argfile order order.json '
  INDEX(inputs.document;  .product) as $dict
  | reduce $order.order[] as $product ([]; . + [$dict[$product]])
  | {document: .}
' [A-Z]*.json

def INDEX

如果您的jq没有INDEX/2,则可能是升级的好时机。或者,您可以简单地添加(添加)其def:

def INDEX(stream; idx_expr):
  reduce stream as $row ({}; .[$row|idx_expr|tostring] = $row);

答案 1 :(得分:1)

这是一个使用order.json确定要由jq读取的文件的解决方案:

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

上面直接举例说明的方法具有许多优点,但是以上内容做出了各种假设,这些假设可能不成立。例如,假设任何文件名中都没有空格。

文件名的严格处理

以下内容假定为有害功能:

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)