1

Given this document:

{
    "slide": [{
        "title": {
            "fontName": "Open Sans",
            "top": 188,
            "left": -22,
            "width": 597,
            "fontSize": 45,
            "valign": "bottom",
            "presetType": "Parallelogram",
            "fill": "#6bcad5",
            "halign": "left",
            "fontColor": "#f4dde6",
            "height": 192
        }
    }, {
        "picture": {
            "top": 25,
            "left": 54,
            "width": 1,
            "colorMode": "GRAYSCALE",
            "presetType": "Snip_Same_Side_Rect",
            "height": 1
        }
    }]
}

The following code returns [54]:

JSONArray obj = ctx.read("$.slide[?(@.picture)].picture.left");

But I need a primitive type, still maintaining the indefinite path.

glytching
  • 44,936
  • 9
  • 114
  • 120
Santhosh Tpixler
  • 361
  • 4
  • 12
  • Looking for naive way of doing this conversion JsonArray to primitive type – Santhosh Tpixler Feb 01 '18 at 15:08
  • Could you provide the JSON against which you are executing this jsonpath? – glytching Feb 01 '18 at 15:09
  • `{ "slide": [{ "title": { "fontName": "Open Sans", "top": 188, "left": -22, "width": 597, "fontSize": 45, "valign": "bottom", "presetType": "Parallelogram", "fill": "#6bcad5", "halign": "left", "fontColor": "#f4dde6", "height": 192 } }, { "picture": { "top": 25, "left": 54, "width": 1, "colorMode": "GRAYSCALE", "presetType": "Snip_Same_Side_Rect", "height": 1 } }] }` – Santhosh Tpixler Feb 02 '18 at 06:52

1 Answers1

1

According to the docs:

Please note, that the return value of jsonPath is an array, which is also a valid JSON structure. So you might want to apply jsonPath to the resulting structure again or use one of your favorite array methods as sort with it.

Note: if you are using the Java implementation then an issue has already been raised for this and the response to that issue reiterated the above point.

So, as long as you use a filter you'll need two calls, for example:

String json = "...";

DocumentContext ctx = JsonPath.parse(json);

// capture the JSONArray
JSONArray obj = ctx.read("$.slide[?(@.picture)].picture.left");

// read the first value from the JSONArray
// prints "54"
System.out.println(obj.get(0)); 

// alternatively, push the JSON representation of the JSONArray back through JsonPath
Integer value = JsonPath.read(obj.toJSONString(), "$[0]");
// prints 54
System.out.println(value);
glytching
  • 44,936
  • 9
  • 114
  • 120