I am trying to use a regex to add quotes to any number in a JSON response. A snippet from the JSON is below. Any help is appreciated.
"videoIds":[2929365783001,2890489654001,2872798368001,...]
I need:
"videoIds":["2929365783001","2890489654001","2872798368001",...]
You can't reliably do it with a regex. Just parse the response as JSON, modify the resulting data structure and re-serialize it as JSON if needed. Here's how I'd do it in Python:
data = json.loads(response)
data["videoIds"] = [str(i) for i in data["videoIds"]]
modified_response = json.dumps(data)
Assuming your JSON string is called str
, you could try several things:
convert the JSON into a JavaScript object and then convert the contents of the "videoIds" array into strings, as in:
var obj=JSON.parse(str), rv=[]; obj.videoIds.forEach(function(elt){ rv.push(elt.toString()); }); obj.videoIds=rv; str=JSON.stringify(obj);
extract the videoIds portion of the str, regex the numbers to add double quotes, and replace it:
var matches=str.match(/"videoIds":\\[([^\\]]+)\\]/), targ=matches[0].replace(/[\\[\\]]/g,function(m){ return '\\\\'+m; }), // escape regex magic chars '[' and ']' nums=matches[2].split(/,/), rv='"videoIds":["'+nums.join('","')+'"]'; str=str.replace(new Regex(targ),rv); // replace the extracted line
But generally, it's probably easier to modify the original object before it is converted to JSON so that all the numbers are actually strings.
This is a regex way in ruby. I assume that except the missing quotes, the JSON is well formed. This code will add quotes to all keys and no-empty values without quotes. Note that this will add double-quotes to values like numbers, true
, false
, null
too.
jsonstr = <<'LOD'
{
menu: {
id: "file",
"value": File,
"popup": {
"videoIds":[2929365783001,2890489654001,2872798368001,...],
toto:titi,
"\"glip":["glop\\",glup]
}
}
}
LOD
jsonstr = jsonstr.gsub(
/(?x)
( # group 1: possible content before a value or key without double quotes
(?>
(?> "(?>[^"\\]++|\\{2}|\\.)*+" )? # content inside double quotes
[\]\[}{:,\s]++ # spaces and special characters
)++
)
( [^\]\[{},:"]+? ) # group 2: value or key without double quotes
(?= \s* (?: [\]:,}] | \z ) )
/,
'\1"\2"')
puts jsonstr
The group 1 is used to skip all keys or values between double quotes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.