用于修复无效 JSON 的正则表达式
Regular expression to fix invalid JSON
我正在对服务进行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
}
}
]
现在,它找到了模式的开始,但更进一步。我相信这与逗号有关。我知道应该发生多种模式匹配,但现在,我只是想让一个工作。提前感谢您的帮助。
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' )
相关文章:
- 将电子邮件验证正则表达式字符串存储在JSON中
- 如何使用 JSON 解析正则表达式文本
- 在JSON中指定正则表达式字符串,在JavaScript和PHP中使用
- 使用正则表达式循环 Json 数据
- JavaScript 使用基于 json 数组的正则表达式替换字符串
- 如何在从 javascript 中的 json 对象中提取字符串时保留转义序列.(字符串实际上是正则表达式模式)
- 如何创建正则表达式 查找 JS 文件(或 JSON)中的所有字符串
- 用于修复无效 JSON 的正则表达式
- 如何在 javascript 中使用正则表达式检查空的 json 响应
- 使用正则表达式转换 JSON 密钥值
- 如何使用正则表达式和“”字符正确解析 JSON
- 如何使这个json正则表达式贪婪
- JSON中的正则表达式模式
- javascript通过使用正则表达式匹配键从JSON对象检索值
- 使用正则表达式从JSON中删除具有给定属性的对象
- 如何从json使用正则表达式(regex)在php中的内容
- 使用正则表达式匹配JSON
- 我如何使用JSON键作为正则表达式
- 检查JSON LIKE字符串是否有效- JS正则表达式
- 是否有一种方法让我搜索JSON数组向后使用正则表达式