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>
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.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.