1

I'm trying to get the value of a specific attribute in a JSON file but instead I get a row content of the array.

For example that's my JSON file:

{
  "head": {
    "vars": [ "type1" , "pred" , "type2" ]
  } ,
  "results": {
    "bindings": [
      {
        "type1": { "type": "Collection" } ,
        "type2": { "type": "has" } ,
        "type3": { "type": "contributor" }
      } ,
      {
        "type1": { "type": "Collection2" } ,
        "type2": { "type": "has2" } ,
        "type3": { "type": "contributor2" }
      } 

]
}
}

I want to get only the values of attribute "type3" But my following code gets me all of them.

JSONObject obj =  new JSONObject(json);      
JSONObject results = obj.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");       

for (int i=0; i<bindings.length(); i++)
{
JSONObject x = bindings.getJSONObject(i);                
x.getJSONObject("type3");  
}

I tried several approaches but it seems I'm doing it wrong.

6
  • why are you iterating on json, which is a single object, shouldnt you be iterating over bindings under result eg .. for (int i=0; i<bindings.length(); i++) Commented Feb 12, 2016 at 4:45
  • I tried with (int i=0; i<bindings.length(); i++) aswell, I just changed to see the results as I was trying other stuff. Thanks for the remarque I 'll update on the question. But Still I don't know how I can get a specific value :( Commented Feb 12, 2016 at 4:48
  • 1
    I think Here, you are getting value of type3 as "{ "type": "contributor2" }" . and thats correct. what else do you want to get ? Commented Feb 12, 2016 at 4:51
  • 1
    I'm actually getting this : "type1": { "type": "Collection" } , "type2": { "type": "has" } , "type3": { "type": "contributor" }. And I only want to get this : { "type": "contributor" }. Commented Feb 12, 2016 at 4:53
  • What specific value do you want? Your code clearly shows you understand when to use an array vs an object. From an object, you can do a simple get on a key Commented Feb 12, 2016 at 4:54

2 Answers 2

2

I only want to get this : { "type": "contributor" }

Then get that value (roughly) like so

bindings.getJSONObject(0).getJSONObject("type3")
Sign up to request clarification or add additional context in comments.

Comments

2

you can use JsonPath.read to get all Type3 values as list.

List value = JsonPath.read(bindings, "..type3");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.