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
  • 1,955
  • 3
  • 25
  • 55
AlGallaf
  • 607
  • 6
  • 14
  • 26

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
  • 376,738
  • 64
  • 519
  • 520
1

use the following code

alert(data.name[0]);
Ashraf Bashir
  • 9,356
  • 13
  • 53
  • 80
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,129
  • 5
  • 43
  • 81
0

try this to loop through all elements

for(x in data)
{
    for(y in data[x])
    {
        alert(data[x][y]);
    }
}
Kanishka Panamaldeniya
  • 16,732
  • 29
  • 117
  • 190