2

我正在对服务进行 API 调用,但它返回了无效的 JSON。photo_url 字段没有用引号封装的 url。我把它作为一个字符串,并试图编写一个正则表达式来在 url 周围添加引号。我用 Javascript 做这一切,使用 Titanium。

这是我现在的代码:

var response = '[{"friend_request":{"about_me":"","friend_id":"11043271728","gender":"M","display_name":"foo","age":21,"photo_url":http:\/\/s.foo.com\/img\/nopic\/MB_90x90_male.gif,"hometown":""},"friend_request":{"hometown":"","display_name":"bar","gender":"M","age":"","friend_id":"11040542298","about_me":"","photo_url":http:\/\/s.foo.com\/img\/nopic\/MB_90x90_male.gif}}]';
var pattern = /http.*(,|\}|\s)/i;
var flip = target.match(pattern);
var foo  = target.replace(flip, "\"" + flip + "\"");
console.log(foo);

这是人类可读形式的 JSON:

[
  {
    "friend_request": {
      "about_me": "",
      "friend_id": "11043271728",
      "gender": "M",
      "display_name": "foo",
      "age": 21,
      "photo_url": http:\/\/s.foo.com\/img\/nopic\/MB_90x90_male.gif,
      "hometown": ""
    },
    "friend_request": {
      "hometown": "",
      "display_name": "bar",
      "gender": "M",
      "age": "",
      "friend_id": "11040542298",
      "about_me": "",
      "photo_url": http:\/\/s.foo.com\/img\/nopic\/MB_90x90_male.gif
    }
  }
]

现在,它正在寻找模式的开始,但会更进一步。我相信它与逗号有关。我知道应该发生多个模式匹配,但现在,我只是想让一个工作。在此先感谢您的帮助。

4

1 回答 1

3
var response = '[{"friend_request":{"about_me":"","friend_id":"11043271728","gender":"M","display_name":"foo","age":21,"photo_url":http:\/\/s.foo.com\/img\/nopic\/MB_90x90_male.gif,"hometown":""},"friend_request":{"hometown":"","display_name":"bar","gender":"M","age":"","friend_id":"11040542298","about_me":"","photo_url":http:\/\/s.foo.com\/img\/nopic\/MB_90x90_male.gif}}]';

var str = response.replace( /("photo_url":)([^,}]+)([,\}])/g, '$1"$2"$3' )
于 2012-05-01T16:47:29.743 回答