Native way to run a forEach loop on an unnamed JSON object

Viewed 169

Example JSON

[
  {
   "id": 12,
   "clientName": "super-client"
  },
  {
   "id": 15,
   "clientName": "helloClient"
  }
]

I want to use JMESPath to check if each clientName field does not contain the text super- and then display the result

I'm using the API connector tool for Google Sheets to parse a JSON I get via a call. I'm stuck with this.

Almost all the reference examples on JMESPath site have a named object or array. This JSON I have doesn't have any named objects.

I want to do something like

result = []
for entry in data:
if not entry['clientName'].find("super-"):
result.append(entry)
return result
2 Answers

In JMESPath, it is called a filter projection and it can be applied on an array right away, without it having to be named.

What you will need on top of a filter projection is the contains function and the not expression !.

All this together gives you this query:

[?!contains(clientName, 'super-')]

Which, on your JSON example will give, as a result:

[
  {
    "id": 15,
    "clientName": "helloClient"
  }
]

Try

function test() {
  var json = [
    {
      "id": 12,
      "clientName": "super-client",
    },
    {
      "id": 15,
      "clientName": "helloClient",
    }
  ]
  var result = json.filter(e => e.clientName.includes('super'))
  console.log(result)
}

  var json = [
    {
      "id": 12,
      "clientName": "super-client",
    },
    {
      "id": 15,
      "clientName": "helloClient",
    }
  ]
  var result = json.filter(e => e.clientName.includes('super'))
  console.log(result)

Related