首页 > 解决方案 > JQ add properties to nested object in nested array

问题描述

I have the following json:

{
  "first": {
    "second" : "A"
  },
  "array": [
    {
      "name" : "AAA",
      "something": {
        "hola": "hi"
      }
    },
    {
      "name" : "BBB",
      "something": {
        "hola": "hi"
      }
    }
  ]
}

I would like to trasform it adding a property to the something object, using the value from the name property of the parent, like:

I have the following json:

{
  "first": {
    "second" : "A"
  },
  "array": [
    {
      "name" : "AAA",
      "something": {
        "hola": "hi",
        "NEW_PROPERTY": "AAA"
      }
    },
    {
      "name" : "BBB",
      "something": {
        "hola": "hi",
        "NEW_PROPERTY": "BBB"
      }
    }
  ]
}

Which jq expression can do this?

标签: jsonjq

解决方案


Try this jq script:

<file jq '.array = [ .array[] | .something.NEW_PROPERTY = .name ]'

This is replacing the array by another one that is the same as the original one with one more key NEW_PROPERTY.


推荐阅读