json - JOLT get key from first element of array and copy to another elements - Stack Overflow

admin2025-04-18  2

I have an array in JSON

[
  {
    "key1": "11",
    "key2": "20"
  },
  {
    "key1": "13"
  },
  {
    "key1": "10"
  }
]

desired

[
  {
    "key1": "1",
    "key2": "2"
  },
  {
    "key1": "13",
    "key2": "2"
  },
  {
    "key1": "10",
    "key2": "2"
  }
]

Thanks in advance

I have an array in JSON

[
  {
    "key1": "11",
    "key2": "20"
  },
  {
    "key1": "13"
  },
  {
    "key1": "10"
  }
]

desired

[
  {
    "key1": "1",
    "key2": "2"
  },
  {
    "key1": "13",
    "key2": "2"
  },
  {
    "key1": "10",
    "key2": "2"
  }
]

Thanks in advance

Share Improve this question edited Jan 30 at 16:25 Barbaros Özhan 65.6k11 gold badges36 silver badges61 bronze badges asked Jan 30 at 16:01 Будён Михайлович СемённыйБудён Михайлович Семённый 312 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 2

You can use the following shift transformation :

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "*": "[&1].&",
        "@1,[0].key2": "[&1].key2"//copy the first occurence to the others
      }
    }
  },
  {
    "operation": "cardinality",
    "spec": {
      "*": {
        "*": "ONE"//remove duplicates
      }
    }
  },
  {//keep the order by tags as 1.key1, 2.key2
    "operation": "sort"
  }
]

or you can directly transfer the value using a modify spec such as :

[
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "*": {
        "~key2": "@(2,[0].key2)"//returns the related value if "key2" does not exist or is null due to the ~ operator
      }
    }
  }
]
转载请注明原文地址:http://anycun.com/QandA/1744907476a89313.html