Reputation: 1053
My web app returns a JSON object. I am simply trying to write the result to a page and the best I can get is 'undefined'.
<p id="demo"></p>
<script>
var text= [
{
"name": "xx",
"street": 65.2067810799497698,
"phone": 134.2967768940979501
}
];
alert(text.name)
document.getElementById("demo").innerHTML =
text.name
;
</script>
Upvotes: 0
Views: 63
Reputation: 4597
You dont need to parse anything, just change text
to text[0]
whenever you are trying to get your value (name, street...) from the first index which is 0
<p id="demo"></p>
<script>
var text= [
{
"name": "xx",
"street": 65.2067810799497698,
"phone": 134.2967768940979501
}
];
alert(text[0].name)
document.getElementById("demo").innerHTML = text[0].name
</script>
Upvotes: 2
Reputation: 11313
You can use JSON.parse(text)
.
[EDIT]:
JSON.parse(text)
would parse text
had it been a string response.
In your case, you have an object inside an array, so add a [0]
to text
like another answer correctly points out as shown:
document.getElementById("demo").innerHTML = text[0].name;
Since this array has only one object nested, you are safe with that without having to loop for different indices.
Upvotes: 3