AlGallaf
AlGallaf

Reputation: 635

Get Data from JSON String

I'm unable to successfully get data from the JSON string below. Using JavaScript, I'm able to alert the full string [ alert(data); ] but I'm unable to get only the first name.

Can someone please help?

var data = {
    "name": [
        "Enid Norgard",
        "Cassie Durrett",
        "Josephine Ervin"
    ],
    "email": [
        "[email protected]",
        "[email protected]",
        "[email protected]"
    ],
    "role": [
        "Gamer",
        "Team Leader",
        "Player"
    ],
    "emp_id": [
        "50",
        "408",
        "520"
    ],
    "id": [
        "234",
        "444",
        "235"
    ]
}

Upvotes: 0

Views: 10835

Answers (5)

Kanishka Panamaldeniya
Kanishka Panamaldeniya

Reputation: 17576

try this to loop through all elements

for(x in data)
{
    for(y in data[x])
    {
        alert(data[x][y]);
    }
}

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Looks like you have a string(because when you use alert the complete text is shown, if it was a object then [Object object] would have shown), first you need to parse it using JSON.parse()

var t = JSON.parse(data)
alert(t.name[0])

Note: Old browsers like IE8 which does not have native support for JSON you have to add a library like json2 to add JSON support

Upvotes: 6

Kingalione
Kingalione

Reputation: 4265

With data.name[0] you will get the name Enid Norgard Similar to that use

data.name[index] 

while index is the position of the name in the innerarray.

If you want only the names array use:

alert(data.name)

Upvotes: 0

Jeremy Voges
Jeremy Voges

Reputation: 41

    //sample code
    var json = '{"result":true,"count":1}',
    obj = JSON.parse(json);
    alert(obj.count);

For the browsers that don't you can implement it using json2.js. Most browsers support JSON.parse(), hope this will help you for detail see link.

Upvotes: 1

Ashraf Bashir
Ashraf Bashir

Reputation: 9804

use the following code

alert(data.name[0]);

Upvotes: 1

Related Questions