Home > Blockchain >  Accesing only key names of json using jsonPath
Accesing only key names of json using jsonPath

Time:10-24

I have a simple question, say I have the following json

{
   "ALPHA":[
      ....
   ],
   "BETA":[
     ....
   ],
   "GAMMA":[
     .....
   ]
}

how do I access the subroot elements, I mean just the names: "ALPHA","BETA","GAMMA" using jsonPath? Be aware that I mean their names not their array!!!

I tried jsonPath("$[*]", ...) but it doesn't work, any sugesstions?

CodePudding user response:

You may consider another library Josson. Just one function keys() can do the job.

https://github.com/octomix/josson

Josson josson = Josson.fromJsonString(
    "{"  
    "   \"ALPHA\":["  
    "      1,2,3,4"  
    "   ],"  
    "   \"BETA\":["  
    "     5,6,7"  
    "   ],"  
    "   \"GAMMA\":["  
    "     8,9"  
    "   ]"  
    "}");
JsonNode node = josson.getNode("keys()");
System.out.println(node.toPrettyString());

Output

[ "ALPHA", "BETA", "GAMMA" ]

CodePudding user response:

Thanks a lot @Raymond Choi, it should also work.

But based on your answer, that I should use the function keys(), I search a lit bit more and I found that jsonPath indeed has his own function.

So the solution to my question is simple:

jsonPath("$.keys())

  • Related