Reputation: 83
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
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
Reputation: 14285
http://forums.ext.net/showthread.php?6084-Consume-Web-Service-from-JavaScript-getting-JSON-response
I will suggest you to use JQuery instead of javascript: Check this: http://www.codeproject.com/Articles/37727/Prepare-a-JSON-Web-Service-and-access-it-with-JQue
Check this, very good for beginner : http://www.json.org/js.html
Beginner JavaScript: Working with JSON and Objects in JavaScript
Upvotes: -1
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
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
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