JOLT script creating duplicate array rows

Viewed 49

I'm trying to write a script that filters a JSON array by if the objects have a key, "parent_json".

Here's the jolt script I wrote:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "parent_info": {
          "": null,
          "*": {
            "@2": "[]"
          }
        }
      }
    }
  }
]

And it works beautifully, with the caveat that it is duplicating the matched rows. Take this input JSON:

[
  {
    "ID": 5,
    "username": "test1",
    "parent_info": {
      "parent_id": 4,
      "parent_username": "test"
    }
  },
  {
    "ID": 4,
    "username": "test"
  },
  {
    "ID": 3,
    "username": "admin1",
    "parent_info": {
      "parent_id": 2,
      "parent_username": "admin"
    }
  },
  {
    "ID": 2,
    "username": "admin"
  }
]

And this output JSON:

[
  {
    "ID": 5,
    "username": "test1",
    "parent_info": {
      "parent_id": 4,
      "parent_username": "test"
    }
  },
  {
    "ID": 5,
    "username": "test1",
    "parent_info": {
      "parent_id": 4,
      "parent_username": "test"
    }
  },
  {
    "ID": 3,
    "username": "admin1",
    "parent_info": {
      "parent_id": 2,
      "parent_username": "admin"
    }
  },
  {
    "ID": 3,
    "username": "admin1",
    "parent_info": {
      "parent_id": 2,
      "parent_username": "admin"
    }
  }
]

Any ideas how I can change the script to not duplicate the output?

1 Answers

Seems you need to pick only the sub-objects containing parent_info attribute. Then just use that as a key name while directly nesting "@1": "" key-value pairs in order no to roam all indexes that causes duplication. Btw, it's enough to use "" as value instead of "[]" such as

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "parent_info": {
          "@1": ""
        }
      }
    }
  }
]

enter image description here

Related