0

I have the following in my HTML5 code which makes use of javascript:

     var myObj = localStorage[dataObj];
     alert(myObj);
     alert(myObj.City);

When I do alert(myObj) it shows {"ID":68,"City":New York} which is what is in var. I now need to get the value of City. I do the following but it shows as undefined: alert(myObj.City); I also tried

    alert(myObj[0]:City) but that did not work as well 
1
  • 2
    @DanielA.White: If alert showed that, it's a string. If you alert an object, you get [object Object]. Commented Mar 22, 2012 at 20:23

2 Answers 2

4

myObj is a string, it needs to be parsed into an object.

myObj = JSON.parse(myObj);
console.log(myObj.City);

P.S. console.log is much better for debugging than alert.

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

2 Comments

IE doesn't seem to support console.log ?
@AlanFoster: IE (< 9, I think) only supports it after you open the developer tools (F12).
1

Looks like you have a string, rather than an object. Load it with:

myObj = JSON.parse(myObj);
alert(myObj.City);

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.