修正无效JSON的正则表达式

时间:2020-12-08 16:03:46

I'm making an API call to a service, but it's returning invalid JSON. The photo_url field doesn't have the url encapsulated in quotes. I have it as a String, and was trying to write a regex to add quotes around the url. I'm doing this all in Javascript, using Titanium.

我正在给一个服务做一个API调用,但是它返回的是无效的JSON。photo_url字段没有将url封装在引号中。我将它作为一个字符串,并试图编写一个regex来在url周围添加引号。我用的是Javascript,用的是Titanium。

This is the code I have now:

这是我现在的代码:

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);

Here's the JSON in human-readable form:

以下是人类可读的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
    }
  }
]

Right now, it's finding the beginning of the pattern, but going on even further. I believe it has something to do with commas. I know there are multiple pattern matches that should happen, but for now, I was just trying to get one to work. Thanks in advance for your help.

现在,它正在寻找模式的开端,但还在继续。我相信这和逗号有关。我知道应该有多种模式匹配,但现在,我只是想让其中一种发挥作用。谢谢你的帮助。

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' )

#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' )