Logesh Mohanasundaram
Logesh Mohanasundaram

Reputation: 83

How to get the json directly from api and use it?

var moviereviewtext = "{"title": "Friday the 13th", "year": 1980, "reviews": [{"reviewer": "Pam", "stars": 3, "text": "Pretty good, but could have used more Jason"}, {"reviewer": "Alice", "stars": 4, "text": "The end was good, but a little unsettling"}]}";

var jsonobj = eval("(" + moviereviewtext + ")");

In the above shown there is a variable and we type the data in json format. But what i need is , i have the url of the api and i have to get the json from there and assign it to the variable. How to do it?

Upvotes: 2

Views: 156

Answers (5)

Alnitak
Alnitak

Reputation: 339816

The simplest solution (although not to everyone's taste) would be to use jQuery to handle making the AJAX request to the server hosting that API:

$.get(url, options).done(function(obj) { 
    // access the object fields here
    var title = obj.title;
    ...
})

jQuery not only handlers browser incompatibilities for you, it parses the JSON too, so your callback function will directly receive a decoded object.

Upvotes: 0

patel.milanb
patel.milanb

Reputation: 5992

this is Jquery if thats waht you are looking for...

          var myVariable = $.ajax({
           url: '/path/to/url',
           dataType: 'json',
        },
           async: false,
           success: function(data){
                           // do whatever
           }
       });

Upvotes: 0

BlueMagma
BlueMagma

Reputation: 2505

Didn't you forget to escape your quote ?

If so you should do that :

var moviereviewtext = "{\"title\": \"Friday the 13th\", ...}";

Or that

var moviereviewtext = "{'title': 'Friday the 13th',  ...}";

Upvotes: 2

Edd Slipszenko
Edd Slipszenko

Reputation: 396

var moviereviewtext = "{\"title\": \"Friday the 13th\", \"year\": 1980, \"reviews\": [{\"reviewer\": \"Pam\", \"stars\": 3, \"text\": \"Pretty good, but could have used more Jason\"}, {\"reviewer\": \"Alice\", \"stars\": 4, \"text\": \"The end was good, but a little unsettling\"}]}";
responseJSON = JSON.parse(moviereviewtext);
alert(responseJSON.title);

Is it JSON.parse() that you are after?

The above code will display the title of the move and the rest of the data can be accessed in the same way using the dot notation.

Also, I believe you forgot to escape your moviereviewtext variable.

Upvotes: 1

Related Questions