Search code examples
jsonjolt

Remove specific elements from json array


Received JSON:

  {
    "id": 313,
    "status": "blocked",
    "audit_pixels": [
      {
        "audit_pixel": "134307&ord={{random}}",
        "id": 1470355,
        "parent_id": null,
        "role": null
      },
      {
        "audit_pixel": "1087125871&ord={{random}}",
        "id": 1470356,
        "parent_id": 1470355,
        "role": "originalShow"
      },
      {
        "audit_pixel": "cid1115596-posid2396249",
        "id": 1470359,
        "parent_id": 1470357,
        "role": "originalShow"
      },
      {
        "audit_pixel": "cid1115596-posid2396249/{{random}}",
        "id": 1470360,
        "parent_id": 1470357,
        "role": "playbackStarted"
      },
      {
        "audit_pixel": "cid1115596-posid2396249/{{random}}",
        "id": 1470361,
        "parent_id": 1470357,
        "role": "playheadReachedValue100"
      }
    ]
  }

I want to remove elements from array audit_pixels:

  • where field role is null,
  • where field role role is not originalShow

EXPECTED RESULT:

  {
    "id": 313,
    "status": "blocked",
    "audit_pixels": [
      {
        "audit_pixel": "1087125871&ord={{random}}",
        "role": "originalShow"
      },
      {
        "audit_pixel": "cid1115596-posid2396249",
        "role": "originalShow"
      }
    ]
  }

Is it possible? I tried with:

[
  {
    "operation": "shift",
    "spec": {
      "*": {
        "id": "[&1].id",
        "status": "[&1].status",
        "audit_pixels": {
          "*": {
            "role": {
              "null": {
                "@(3,id)": "null"
              },
              "originalShow": {
                "@(3,id)": "audit_pixels.[&1]"
              }
            }
          }
        }
      }
    }
  }
]

Solution

  • You can use the following transformation :

    [
      {
        "operation": "shift",
        "spec": {
          "*": "&",
          "audit_pixels": {
            "*": {
              "*": "&2.@1,role.@1,id.&"
            }
          }
        }
      },
      {
        "operation": "shift",
        "spec": {
          "*": "&",
          "audit_pixels": {
            "originalShow": {
              "*": {
                "audit_pixel|role": "&3[#2].&"
              }
            }
          }
        }
      }
    ]
    

    the demo on the site https://jolt-demo.appspot.com/ is :

    enter image description here