Reputation: 7709
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.
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:
[
{
"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.
Upvotes: 2
Views: 3093
Reputation: 207557
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' )
Upvotes: 3