Gio Bact
Gio Bact

Reputation: 541

Get a specific element from JSON

I know this is a very simple and common question; I've already read some Q/A but I can't figure out how to solve my problem.

I have this short json from an AJAX call that execute a SPARQL query:

{
  "head": {
    "vars": [ "name" , "email" ]
  } ,
  "results": {
    "bindings": [
      {
        "name": { "type": "literal" , "value": "Name Surname" } ,
        "email": { "type": "literal" , "value": "[email protected]" }
      }
    ]
  }
}

I'm searching name and email of a single user of the application, so the result should be always made up of a single element.

What I want to retrieve is the "name" of the user. I tried something like:

response["name"].value
//or
response[0]["name"]
//or
response.name

but always wrong.

How can I get the name value? Thanks to everyone who will help.

Upvotes: 0

Views: 89

Answers (3)

Oleksandr T.
Oleksandr T.

Reputation: 77482

Try this

response.results.bindings[0].name.value
response.results.bindings[0].email.value

Update

Example

Upvotes: 2

aarjithn
aarjithn

Reputation: 1181

In JSON, you always have to provide the full path to the property you like to reach. Assuming you have stored the parsed JSON in variable response, the following paths will get you corresponding value.

response.results.bindings[0].name.value for name response.results.bindings[0].email.value for email

Recommend you to go through http://www.copterlabs.com/blog/json-what-it-is-how-it-works-how-to-use-it/ to get basic concepts of JSON.

Upvotes: 1

Aadil Keshwani
Aadil Keshwani

Reputation: 1386

You can check out the fiddle created here

http://jsfiddle.net/uqxp4j73/

The code for this is as under

var x='{ "head": { "vars": [ "name" , "email" ]   } ,  "results": {  "bindings": [       {         "name": { "type": "literal" , "value": "aadil keshwani" } ,         "email": { "type": "literal" , "value": "[email protected]" }       }     ]   }}';
obj = JSON && JSON.parse(x) || $.parseJSON(x);
console.log(obj);
console.log(obj["results"]["bindings"][0]["name"]["value"]);
alert(obj["results"]["bindings"][0]["name"]["value"]);

Hope this helps :)

Upvotes: 1

Related Questions