adund cn
adund cn

Reputation: 25

Store JSON data into a variable using Javascript

I have an array variable and the value is shown below:

var data=[{"id":"1"},{"id":"2"}];

but what I need to get the data value from json url http://myweb.com/student/wp-json/wp/v2/posts

the url content is:

[{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"},{"id":"5"},{"id":"6"}]

without semicolon as ending

The question is how to store the value returned from Json into an variable.

Upvotes: 0

Views: 4411

Answers (1)

Nagaraja Thangavelu
Nagaraja Thangavelu

Reputation: 1168

So, you need to get the JSON data from URL and store in a variable?

You can do following:

function get_data_from_url(url){
    var http_req = new XMLHttpRequest();
    http_req.open("GET",url,false);
    http_req.send(null);
    return http_req.responseText;          
}

var data_url = "http://myweb.com/student/wp-json/wp/v2/posts";
var data_obj = JSON.parse(get_data_from_url(data_url));
console.log("Data object: "+ data_obj);

Upvotes: 2

Related Questions