0

I have a simple JSON(below). The content in the modified array element may vary. I need to have a fixed output whenever the modified element has at least one file name that starts with 'test/' and a different output if none of the file starts with 'test/'. I need to do that using JsonPath.

So far all the expressions I have used (e.g. $.commits[].[?(@ =~ /test.*?/i)]) gives me the list of files if the expression is matched, I need to have a fixed value (true or false) not the modified[] element value, if any of the array element in the modified element starts with 'test'.

Any help will be much appreciated.

{"commits":[{"modified":["test/db/ecs-db.sql","test/infra/infra-settings.json","test1/code/code.java"]}]}

1 Answers1

1

The definition of JSONPath is:

JSONPath defines expressions to traverse through a JSON document to extract a subset of the JSON

All you can get back is "a subset of the original JSON". The result of a JSONPath is always JSON. Since true and false are not valid JSON, you can't get either of them back as a result. You could get back a JSON structure containing true or false, but only if those values were in the original JSON.

What is normally done here is that you get back the resulting JSON, and then you test that to determine if it matches some criteria or not. In your case, you expect to always get back an array of paths. Your criteria is "is the resulting list empty?". So you need to test if the list you get back is empty or not to arrive at your "fixed value" of true or false.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44
  • Thanks @Steve, unfortunately I am not using any programming language like Java or Python here. The expression is getting executed in Terraform and the value selected by the JsonPath expression must match the hard coded value specified in the another field. So as long as I can get a constant value out of the JsonPath expression if any of the array elements starts with **test/** or don't , then I can compare that with another value. As you mentioned is there any way to test "is the resulting list empty?" in JsonPath ? – Soumya Barman Sep 08 '20 at 01:48
  • Can you maybe test for "[]"? - I would think you could, as I'd expect that you're dealing with a JSON string rather than the expanded form. Again, it can't be a JSONPath thing. It will have to be a Terraform thing. I love Terraform, but I haven't done anything very fancy with it, and certainly haven't run into this issue :) – CryptoFool Sep 08 '20 at 02:01