JavaScript to Handle REST JSON Feed

2019-07-25 00:55发布

Trying to figure out the JavaScript syntax for handling JSON feed returned by a REST service. Suppose a random REST service (e.g. http://random.service/directory) is returning the following feed:

{
  'firstName': 'John',
  'lastName': 'Smith',
  'address': {
      'streetAddress': '21 2nd Street',
      'city': 'New York'
  }
}

and that I have a JSON parsing JS function (to parse the above feed) like:

function parseRESTFeed(json) {
  ...
}

How do I bridge the REST call of "http://random.service/hello" to parseRESTFeed(json) via JS?

Much Thanks!

1条回答
在下西门庆
2楼-- · 2019-07-25 01:44

If you use jQuery (and you should if you don't), then you can do it like this (ref):

$.getJSON('http://random.service/directory', null, function(data){
    // And here you can do whatever you want with "data", no need to parse it
    alert(data.firstName);
});

If you have some other way to get response from the service as string, again there is no reason to parse, since you can use javascript's eval. For example:

var myJSON = "{'firstName': 'John','lastNAme': 'Smith'}";
var data = eval('(' + myJSON + ')');
alert(data.firstName);
查看更多
登录 后发表回答