You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Consider serializing RegExp objects to strings #91
PCRE is now the main regex format, included into stdlibs of the most of languages. Why not to allow inserting literal regexes into JSON5 document?
Reacted by Martin Ždila, pankaramp, Scott Taylor, Szymon Marczak, Wu Haotian, Kim Schmider, Aaditya Taparia, Jonathan Aldrich, cimak, Peter Becker and 3 more
I've thought about this, but it isn't really a feature that anyone has been asking for or that seems to be lacking. Without that demand, this probably won't get implemented.
(Also, who would want to write a parser for a regex expression?)
Here's a few examples that would fail if we treated everything between two / as a RegExp:
/\//(//)//[//*//+//?/
We would also need to parse trailing flags (g, i, m).
We could try to eval anything between two / and see if a RegExp comes out, but that would be a blatant security risk.
Also, ECMAScript doesn't support full PCRE. Specifically, it doesn't support recursion, look-behind, directives, conditionals, atomic groups, named capture, comments, or embedded code. So, JSON5 cannot represent PCRE without breaking ES5 compatibility. Ultimately, this means that platforms that support PCRE wouldn't be able to serialize PCRE as JSON5.
The best way to serialize regular expressions is to convert them to strings.
Reacted by Kim Schmider, xpoback, Andreas **Felix** Häberle, stefnotch and Slava
It still seems that there is some desire to implement regular expressions as first class values in JSON5. So, I'm going to elaborate on why I think it's a bad idea.
Parsing
I've already established that if you just treat everything between two / characters as a regular expression you'd have to use the native platform's regular expression parser to ensure it's valid. Bet let me entertain that idea and see how easy it would be to implement it.
First, you'd need to make sure that at least one character exists between the two /s because // is a comment in JSON5.
// <- comment/a/<-RegExp
Now, what happens if you want to match a / in your regular expression? You need to escape it with a \ character.
/a\/b/// matches 'a/b'
Okay, so any occurrences of \/ should not terminate a regular expression. But what about this regular expression:
/a\\/// matches 'a\\'
It has an occurrence of \/ but the \ is escaped as \\. So we need to check for occurrences of \\ and \/.
Okay, we're done, right? Well, what about this regular expression?
/a[b/c]d/// matches 'abd', 'a/d' and 'acd'
It's a valid regular expression with an unescaped / because it's inside an alternation group […]. So now we need to track when an alternation group begins and ends. Not so difficult, right?
/a\[bc]d/// matches 'a[bc]d'/a[b[c]d/// matches 'abd', 'a[d' and 'acd'/a[bc\]d/// error: alternation group is never closed
Okay, so in the first example the [ is escaped, but the ] isn't because it only has special meaning in an alternation group. In the second example, the second [ is not escaped but doesn't start new alternation group. The third example is self-explanatory. So, we need to check for [, ], \[, and \], and treat [ and ] differently depending on whether or not we're in a alternation group.
Does that cover our bases? I don't know, but for the sake of argument, let's just say it does.
Let's simplify this into a list of steps:
When parsing a JSON5 value, if the first non-whitespace character is /:
Peek the next character, and if it is /, parse a comment, and do not perform subsequent steps. (Otherwise, assume it's a regular expression.)
Let p = "". p will store the regular expression pattern.
Let f = "". f will store the regular expression flags.
Let a = false. a will indicate whether we are in an alternation group.
Let c = the next character read from the stream of characters.
If c is / and a is false, skip to step 14.
If c is / and a is true, concatenate c onto p, and return to step 6.
If c is [, set a to true, concatenate c onto p, and return to step 6.
If c is ], set a to false, concatenate c onto p, and return to step 6.
If c is \, concatenate c and the next character in the stream onto p, and return to step 6.
If the end of the stream has been reached, throw a parsing error.
Concatenate c onto p, and return to step 6.
Let c = the next character read from the stream.
If c matches the IdentifierPart production, concatenate c onto f, and return to step 14.
Try to instantiate a RegExp object with the arguments p and f.
Step 16 parses the flags according to the ES5 spec. This would allow implementation specific flags to be used (e.g. ES5 doesn't support the s flag, but does support the non-standard y flag).
Besides the fact that this extremely minimal regular expression parser is still relatively complex, it doesn't actually parse the regular expression. There's no way to validate the regular expression in an implementation agnostic way without writing way more code.
We would also need to define what happens if a platform doesn't support regular expressions or can't parse the regular expression given. It wouldn't know until it tried to parse it.
So, all JSON5 documents that include regular expressions would have to be late-validated, and there would be no true JSON5 validator.
Implementation Agnostic vs Implementation Specific
Let's say we did implement a full regular expression parser according to the ES5 spec. It would no longer be implementation agnostic, and we would expect all implementations of JSON5 to parse JSON5 regular expressions into an ES5 compatible format on its native platform.
Further, by creating an implementation restricted parser you're castrating the more powerful regular expression engines supported by other platforms. No more named captures, no more comments, no more look-behind, no more recursion, no more s flag (dot matches new line).
Solution
JSON.stringify serializes a RegExp instance as en empty object ({}). You can modify that behavior by executing the following line of code:
I've re-opened this issue to discuss whether JSON5 should serialize RegExp objects to strings and how it would be implemented.
I'm not suggesting that we treat RegExps as first class JSON5 values, nor would JSON5 automatically parse a RegExp out of a string. It would work similarly to how Dates work in JSON, where they are serialized into ISO 8601 format but date strings are not automatically parsed as Date objects.
The JSON5 aims to make it easier for humans to write and maintain by hand. It does this by adding some minimal syntax features directly from ECMAScript 5.
If implement RegExp or Date, the JSON5 can't convert to JSON.
I can't hope this.
I have a other suggestion, create a package call json5-regexp or json5-date. And expose a use method in JSON5 to use json5-regexp middleware.
I have a other suggestion, create a package call json5-regexp or json5-date. And expose a use method in JSON5 to use json5-regexp middleware.
Not a bad idea, but this would mostly host reviver functions if we want to still being compatible with JSON or with JSON5 implementations without support for this extensions. Also, if we use embeded strings this revivers could be used with plain JSON too...
const replacer = (k, v) => v instanceof Function ? 'I tried to serialize a function with JSON5, but all I got was this stupid string.' : v
JSON5.stringify(replacer, replacer) // CUE THE BRAAAAM https://youtu.be/YoHD9XEInc0?t=1m1s
@kussmaul Thanks for the suggestion, however the reviver function already works with arrays. The internalize function uses the in operator on all object types. Arrays are objects and the in operator works on their indices.
Triage note after the v3 work: regex literals aren't part of the JSON5 spec, so adding them is a question for json5/json5-spec rather than something this parser can take on by itself. The replacer/reviver approach above (and the regexp-reviver gist) already covers serializing regexes to strings and back. I'd propose closing this here as not planned. @jordanbtucker ok with that, or do you want it kept open to track the spec side?
Activity
jordanbtucker commentedon Oct 9, 2015
I've thought about this, but it isn't really a feature that anyone has been asking for or that seems to be lacking. Without that demand, this probably won't get implemented.
(Also, who would want to write a parser for a regex expression?)
alexpusch commentedon Nov 7, 2015
Came here to suggest the same thing. Something like
I think it would be enough to try to convert anything between two / into a RegExp, why would you need to parse the actual expression?
jordanbtucker commentedon Nov 7, 2015
Here's a few examples that would fail if we treated everything between two
/as aRegExp:We would also need to parse trailing flags (
g,i,m).We could
trytoevalanything between two/and see if aRegExpcomes out, but that would be a blatant security risk.Also, ECMAScript doesn't support full PCRE. Specifically, it doesn't support recursion, look-behind, directives, conditionals, atomic groups, named capture, comments, or embedded code. So, JSON5 cannot represent PCRE without breaking ES5 compatibility. Ultimately, this means that platforms that support PCRE wouldn't be able to serialize PCRE as JSON5.
The best way to serialize regular expressions is to convert them to strings.
jordanbtucker commentedon Mar 15, 2016
It still seems that there is some desire to implement regular expressions as first class values in JSON5. So, I'm going to elaborate on why I think it's a bad idea.
Parsing
I've already established that if you just treat everything between two
/characters as a regular expression you'd have to use the native platform's regular expression parser to ensure it's valid. Bet let me entertain that idea and see how easy it would be to implement it.First, you'd need to make sure that at least one character exists between the two
/s because//is a comment in JSON5.Now, what happens if you want to match a
/in your regular expression? You need to escape it with a\character.Okay, so any occurrences of
\/should not terminate a regular expression. But what about this regular expression:It has an occurrence of
\/but the\is escaped as\\. So we need to check for occurrences of\\and\/.Okay, we're done, right? Well, what about this regular expression?
It's a valid regular expression with an unescaped
/because it's inside an alternation group[…]. So now we need to track when an alternation group begins and ends. Not so difficult, right?Okay, so in the first example the
[is escaped, but the]isn't because it only has special meaning in an alternation group. In the second example, the second[is not escaped but doesn't start new alternation group. The third example is self-explanatory. So, we need to check for[,],\[, and\], and treat[and]differently depending on whether or not we're in a alternation group.Does that cover our bases? I don't know, but for the sake of argument, let's just say it does.
Let's simplify this into a list of steps:
/:/, parse a comment, and do not perform subsequent steps. (Otherwise, assume it's a regular expression.)/and a is false, skip to step 14./and a is true, concatenate c onto p, and return to step 6.[, set a to true, concatenate c onto p, and return to step 6.], set a to false, concatenate c onto p, and return to step 6.\, concatenate c and the next character in the stream onto p, and return to step 6.RegExpobject with the arguments p and f.Step 16 parses the flags according to the ES5 spec. This would allow implementation specific flags to be used (e.g. ES5 doesn't support the
sflag, but does support the non-standardyflag).Besides the fact that this extremely minimal regular expression parser is still relatively complex, it doesn't actually parse the regular expression. There's no way to validate the regular expression in an implementation agnostic way without writing way more code.
We would also need to define what happens if a platform doesn't support regular expressions or can't parse the regular expression given. It wouldn't know until it tried to parse it.
So, all JSON5 documents that include regular expressions would have to be late-validated, and there would be no true JSON5 validator.
Implementation Agnostic vs Implementation Specific
Let's say we did implement a full regular expression parser according to the ES5 spec. It would no longer be implementation agnostic, and we would expect all implementations of JSON5 to parse JSON5 regular expressions into an ES5 compatible format on its native platform.
Further, by creating an implementation restricted parser you're castrating the more powerful regular expression engines supported by other platforms. No more named captures, no more comments, no more look-behind, no more recursion, no more
sflag (dot matches new line).Solution
JSON.stringifyserializes aRegExpinstance as en empty object ({}). You can modify that behavior by executing the following line of code:That's all you need to do to write code like:
As an added bonus, that same line of code also applies to
JSON5.stringifybecause JSON5 also checks fortoJSON().[-]Regexes[/-][+]Consider serializing RegExp objects to strings[/+]jordanbtucker commentedon Mar 16, 2016
I've re-opened this issue to discuss whether JSON5 should serialize
RegExpobjects to strings and how it would be implemented.I'm not suggesting that we treat
RegExps as first class JSON5 values, nor would JSON5 automatically parse aRegExpout of a string. It would work similarly to howDates work in JSON, where they are serialized into ISO 8601 format but date strings are not automatically parsed asDateobjects.XGHeaven commentedon Mar 17, 2016
I think no...
In README.md
If implement
RegExporDate, theJSON5can't convert toJSON.I can't hope this.
I have a other suggestion, create a package call
json5-regexporjson5-date. And expose ausemethod inJSON5to usejson5-regexpmiddleware.piranna commentedon Mar 17, 2016
If we embed RegExp or Date inside string, they are plain strings accepted by JSON, so no problem here. In fact, this "trick" is currently used on JSON sucessfully. The only thing is that JSON needs a special reviver function to interpret the strings that have embeded a RegExp or Date object, like https://github.com/piranna/ContextBroker/blob/master/lib/reviver.js
Not a bad idea, but this would mostly host reviver functions if we want to still being compatible with JSON or with JSON5 implementations without support for this extensions. Also, if we use embeded strings this revivers could be used with plain JSON too...
4 remaining items
aseemk commentedon Sep 30, 2017
I totally forgot about that rant. It's a good one!
Then I guess I end up back with a conservative stance of "let's not take this on right now". =)
aseemk commentedon Sep 30, 2017
Also great point about Date. Yuck.
jordanbtucker commentedon Sep 30, 2017
Funny thing about that rant. I actually used that algorithm to implement this experimental feature.
bluelovers commentedon Mar 2, 2018
@jordanbtucker how about just use
.toString()?i think
"/abc/g"is better than{}jordanbtucker commentedon Mar 2, 2018
@bluelovers I agree. That's what this experimental feature does.
json5/src/stringify.js
Lines 91 to 93 in a6c2b14
bluelovers commentedon Mar 2, 2018
@jordanbtucker already have? but today i still get
{}in node.jsjordanbtucker commentedon Mar 2, 2018
@bluelovers It has only been implemented in this experimental feature. It's not part of the main code.
You can use this
replacerfunction for now.bluelovers commentedon Mar 2, 2018
also maybe for function too? not
nulljordanbtucker commentedon Mar 2, 2018
For functions, use this
replacer:Okay, enough kidding around. See #132, #158, and #106 (comment)
gajus commentedon May 4, 2021
Was the
{regExps: true,}ever released?jordanbtucker commentedon May 4, 2021
@gajus No, but you can use this reviver function to achieve the same result.
https://github.com/json5/json5/blob/v1.0.0-regexps/src/parse.js#L51-L115
The
util.isIdContinueCharfunction can be imported fromjson5/lib/util.Or you can use this self-contained regexp-reviver.js gist.
kussmaul commentedon May 23, 2022
jordanbtucker commentedon May 23, 2022
@kussmaul Thanks for the suggestion, however the reviver function already works with arrays. The
internalizefunction uses theinoperator on allobjecttypes. Arrays are objects and theinoperator works on their indices.kussmaul commentedon May 23, 2022
@jordanbtucker Oops, my bad, I should have looked more closely. Thank you for the prompt feedback!
bybraveHQ commentedon Oct 19, 2026
Triage note after the v3 work: regex literals aren't part of the JSON5 spec, so adding them is a question for json5/json5-spec rather than something this parser can take on by itself. The replacer/reviver approach above (and the regexp-reviver gist) already covers serializing regexes to strings and back. I'd propose closing this here as not planned. @jordanbtucker ok with that, or do you want it kept open to track the spec side?