用于处理REST JSON Feed的JavaScript

时间:2012-03-31 21:13:26

标签: javascript json rest

尝试找出用于处理REST服务返回的JSON提要的JavaScript语法。假设随机REST服务(例如http://random.service/directory)正在返回以下Feed:

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

我有一个JSON解析JS函数(解析上面的feed),如:

function parseRESTFeed(json) {
  ...
}

如何通过JS将“http://random.service/hello”的REST调用桥接到parseRESTFeed(json)?

非常感谢!

1 个答案:

答案 0 :(得分:1)

如果您使用jQuery(如果不这样做则应该使用),那么您可以这样做(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);
});

如果您有其他方式从服务获取响应作为字符串,再次没有理由解析,因为您可以使用javascript的eval。例如:

var myJSON = "{'firstName': 'John','lastNAme': 'Smith'}";
var data = eval('(' + myJSON + ')');
alert(data.firstName);