JSON Path - Extract key

Hi,
I’m using JSON Path — NodePit to extract the data from a JSON like:

{
  "data" : {
    "type" : "articles",
    "id" : "1",
    "attributes" : {
      "type" : {
        "integer" : "Intero"
      },
      "flag-1" : [ "No" ],
      "flag-2" : {
        "1" : "Si"
      }
    }
  }
}

I need to extract the keys of “type”, “flag-1” and “flag-2”.

I tried $['data']['attributes']['type'].*~ according to json-path/JsonPath: Java JsonPath implementation (github.com) but it return the value “Intero”.

Same problem with $['data']['attributes']['flag-2'].*~ that return “Si” instead “1”
and with $['data']['attributes']['flag-1'].*~ that return “No” instead 0 (I think it must return an integer not a string in this case).

Is there a way to have keys instead of values?

Hi @Razzo

Perhaps you could do something like this:

First step is to get all the paths of keys type, flag1 and flag2 by using $['data']['attributes']['type'][*] , $['data']['attributes']['flag-1'][*] and $['data']['attributes']['flag-2'][*].

Since this returns a list, convert it to a string by using the Ungroup node. Thereafter you are looking for the last element in the string seperated by []. If you use

if (column("type") != null) {
    regexReplace(column("type"),".*\\[(.*?)\\].*?$","$1")
} else {
    null
}

in a Column Expression node it is possible to retrieve the key value.

You can perform a small clean-up thereafter or make a nested function like replace(regexReplace(column("type"),".*\\[(.*?)\\].*?$","$1"),"'","").

This method also work whenever the number of keys is higher.

image

Hope this helps!

3 Likes

@ArjenEX Wow! Excellent solution. It works perfectly!

Thank you for the very quick response

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.