How to save parsed JSON?

Hi guys I am trying to put the object I parsed from json to a variable so I can work with it.

    var xmlhttp = new XMLHttpRequest(),

        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                json = JSON.parse(xmlhttp.responseText);
                var obj = json;
        }'GET','', true);
        //var obj - I want it to be stored here.

I’d suggest you to use google before asking.

I’ve googled XMLHttpRequest response and I got this:

Basically, the XHR’s request is stored inside the xmlhttp object in a property called response. The only “problem” is that XHR doesn’t return a JSON object, so you’ll have to parse it to JSON by yourself using the JSON object.

Good luck :slight_smile:

You should look Into javascript closures!

You defind var obj within your callback and therefore it’s only available inside of the callback function. Try declaring obj outside of the callback.

But make sure you don’t continue your function until you’ve recieved your JSON!

Apparently a word disappeared into cyberspace…


Are you going to reuse the information stored in the json object to do something totally different from the obj variable? If not, you may not need to define a obj variable and store the json in it - you could have simply defined obj instead of json in line2.

Did you get an array of objects when you console.log(json)? To pull out the information that you need, don’t forget that you need to

  1. reference the index of the object that you need
  2. use either bracket notation or dot notation to obtain the exact field that you need.

Hopefully I make some sort of sense, if not - do not hesitate to ask me to clarify.

We can parse the message with JSON in JavaScript by using the method String.parseJSON(filter). It parses the JSON message to a string or object. The parameter filter is optional in this method which is used to filter message or transform their results. This method internally uses the JavaScript’s method eval() to parse messages.Check this helpful and useful link.i think it will help you.

maybe you need to write before the if the var obj?
im a student so i dont know too much about your problem but some times its fix my problem.
i mean the placement. :slight_smile: