正则表达式来修复无效的JSON

时间:2012-05-01 16:38:56

标签: javascript regex json

我正在对服务进行API调用,但它返回的是无效的JSON。 photo_url字段没有用引号括起来的url。我把它作为一个字符串,并试图写一个正则表达式在网址周围添加引号。我使用Titanium在Javascript中完成所有操作。

这是我现在的代码:

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
    }
  }
]

现在,它正在寻找模式的开始,但还会继续下去。我相信它与逗号有关。我知道应该发生多种模式匹配,但就目前而言,我只是想让一个模式匹配。在此先感谢您的帮助。

1 个答案:

答案 0 :(得分: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' )