Как объединить объекты с уникальным InstanceId в оболочке bash? - PullRequest
0 голосов
/ 12 декабря 2018

У меня есть два файла json, как показано ниже:

Я хочу объединить объекты в tmp1.json и tmp2.json с уникальным значением InstanceId в оболочке bash.

Я пробовал jq с опцией argjsonно моя версия JQ 1.4 не поддерживает эту опцию.Извините, я не могу обновить jq до версии 1.5.

#cat tmp1.json
{
  "VolumeId": "vol-046e0be08ac95095a",
  "Instances": [
    {
      "InstanceId": "i-020ce1b2ad08fa6bd"
    }
  ]
}
{
  "VolumeId": "vol-007253a7d24c1c668",
  "Instances": [
    {
      "InstanceId": "i-0c0650c15b099b993"
    }
  ]
}

#cat tmp2.json
{
  "InstanceId": "i-0c0650c15b099b993",
  "InstanceName": "Test1"
}
{
  "InstanceId": "i-020ce1b2ad08fa6bd",
  "InstanceName": "Test"
}

Мое желаемое:

{
      "VolumeId": "vol-046e0be08ac95095a",
      "Instances": [
        {
          "InstanceId": "i-020ce1b2ad08fa6bd"
          "InstanceName": "Test"
        }
      ]
    }
    {
      "VolumeId": "vol-007253a7d24c1c668",
      "Instances": [
        {
          "InstanceId": "i-0c0650c15b099b993"
          "InstanceName": "Test1"
        }
      ]
    }

Ответы [ 2 ]

0 голосов
/ 12 декабря 2018
  1. сверните два файла json
  2. попробуйте следующую команду:

    cat tmp2.json|jq -r '"\(.InstanceId) \(.InstanceName)"'|xargs -n2 sh -c 'cat tmp1.json|jq "if .Instances[0].InstanceId==\"$0\" then .Instances[0].InstanceName=\"$1\" else empty end"'
    

Вот вывод:

{
  "VolumeId": "vol-007253a7d24c1c668",
  "Instances": [
    {
      "InstanceId": "i-0c0650c15b099b993",
      "InstanceName": "Test1"
    }
  ]
}
{
  "VolumeId": "vol-046e0be08ac95095a",
  "Instances": [
    {
      "InstanceId": "i-020ce1b2ad08fa6bd",
      "InstanceName": "Test"
    }
  ]
}
0 голосов
/ 12 декабря 2018
#!/bin/bash

JQ=jq-1.4

# For ease of understanding, the following is a bit more verbose than
# necessary.  
# One way to get around the constraints of using jq 1.4 is
# to use the "slurp" option so that the contents of the two files can
# be kept separately.

# Note that jq 1.6 includes the following def of INDEX, but we can use it with jq 1.4.

($JQ -s . tmp1.json ; $JQ -s . tmp2.json) | $JQ -s '

def INDEX(stream; idx_expr):
  reduce stream as $row ({};
    .[$row|idx_expr|
      if type != "string" then tojson
      else .
      end] |= $row);

.[0] as $tmp1
| .[1] as $tmp2
| INDEX($tmp2[]; .InstanceId) as $dict
| $tmp1
| map( .Instances |= map(.InstanceName = $dict[.InstanceId].InstanceName))
| .[]
'

Обтекаемый

INDEX(.[1][]; .InstanceId) as $dict
| .[0][]
| .Instances |= map(.InstanceName = $dict[.InstanceId].InstanceName)
...