0

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>
1
  • 1
    remember in this case text is in square brackets - so try text[0].name ? Commented Jul 8, 2016 at 0:50

2 Answers 2

3

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.

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

3 Comments

I started with this, but I think it's a JSON object not a string in JSON format
JSON.parse ?? but why ?
I thought he couldn't parse the string. I'm updating @John.
2

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>

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.