1

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": [
        "TheWoozyGamer@gmail.com",
        "TheHabitualGamer@gmail.com",
        "TheUptightGamer@gmail.com"
    ],
    "role": [
        "Gamer",
        "Team Leader",
        "Player"
    ],
    "emp_id": [
        "50",
        "408",
        "520"
    ],
    "id": [
        "234",
        "444",
        "235"
    ]
}
Jakub Pomykała
  • 2,082
  • 3
  • 27
  • 58
AlGallaf
  • 627
  • 6
  • 15
  • 28

5 Answers5

6

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

use the following code

alert(data.name[0]);
Ashraf Bashir
  • 9,686
  • 15
  • 57
  • 82
1
    //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.

Community
  • 1
  • 1
0

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)
Kingalione
  • 4,237
  • 6
  • 49
  • 84
0

try this to loop through all elements

for(x in data)
{
    for(y in data[x])
    {
        alert(data[x][y]);
    }
}
Kanishka Panamaldeniya
  • 17,302
  • 31
  • 123
  • 193