How to save parsed JSON?

How to save parsed JSON?
0.0 0

#1

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(),
        json;

        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                json = JSON.parse(xmlhttp.responseText);
                console.log(json);
                var obj = json;
            }
        }

        xmlhttp.open('GET','http://output.jsbin.com/vawamasaci.json', true);
        xmlhttp.send();
        //var obj - I want it to be stored here.

#2

I’d suggest you to use google before asking.

I’ve googled XMLHttpRequest response and I got this: http://stackoverflow.com/a/3038972

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:


#3

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!

Edit:
Apparently a word disappeared into cyberspace…


#4

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.


#6

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.

https://www.mindstick.com/Forum/699/how-to-parse-into-json-object-using-json-parse-in-node-js

https://temboo.com/processing/parsing-json


#7

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: