3

I am currently working with Java, reading JSON response from a webservice. Till now I have been parsing JSON for a path known in advance. So I am able to make objects and arrays depending on situation.

String jsonText = readAll(br);
JSONObject json = new JSONObject(jsonText);
JSONObject resp = json.getJSONObject("Response");

But now I have a problem. I have to ask user to provide me a path and I have to get the value at that path in JSON response. Path could be incorrect - return error in that case.

Kind of like XPath in XML. Do we have something similar in JSON?

Path could for example look like: /Response/VehicleSearch/Vehicles/Vehicle[2]/Features/Feature[7]/ID

Please excuse me if its a stupid question. Any help is appreciated. Thanks in advance.

5
  • try using GSON , a google library for dealing with JSON Commented Aug 30, 2013 at 18:01
  • 1
    For a solution with Gson, see here: stackoverflow.com/questions/15658124/… Commented Aug 30, 2013 at 18:10
  • You have the JSON decomposed into a tree structure. You access that with a "path" just as you'd access the XML, though you may have to step through the branches yourself vs using a path notation. Commented Aug 30, 2013 at 19:04
  • 1
    (This is not a "stupid" question, but you've obviously not put much effort into research.) Commented Aug 30, 2013 at 19:04
  • I did look up and found json-path. I am currently playing with it and having some problem for which I posted another question. I am kind of on a short leash with this one hence posted the question right off. Commented Aug 30, 2013 at 19:09

1 Answer 1

6

For JSON equivalent of XPATH for XML you can use JsonPath

As per docs:

JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPath is available in many programming languages such as Javascript, Python and PHP. Now also in Java!

Sign up to request clarification or add additional context in comments.

3 Comments

Nice. I didn't know this one but it's surely quite handy for lots of occasions.
Thanks Anubhava for pointing to jsonpath. I am currently trying to play with jsonpath but having some problem: stackoverflow.com/questions/18539862/….
Sorry just got back and realized you've resolved the problem on other thread.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.