0

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"
    ]
}
4
  • 2
    The first name is in data.name[0] Commented Aug 22, 2013 at 9:25
  • I get the following error Uncaught TypeError: Cannot read property '0' of undefined Commented Aug 22, 2013 at 9:28
  • this works -> data.name[0] , but i think your real codde is a different one , please provide the real code Commented Aug 22, 2013 at 9:37
  • This question lies in its presentation of existing code. data should be wrapped in quotes as in "real life" it is a string, as the accepted answer indicates. Commented Nov 9, 2023 at 16:23

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

2 Comments

@Paul not alert({"hello":"world"})
JSON.parse solved the issue as I wasn't parsing the string. Thank you.
1

use the following code

alert(data.name[0]);

2 Comments

I get the following error Uncaught TypeError: Cannot read property '0' of undefined
I think you didn't provide your real code, check a running version here: jsfiddle.net/qzv6B
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.

Comments

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)

Comments

0

try this to loop through all elements

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

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.