Reputation: 39
I have a valid regex
(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+
This is available at and can be validated at https://www.regextester.com/94502
Now I a trying to create a JSON in which the above expression is used as a value.
{
"regex": "^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$"
}
This can be verified at https://jsonlint.com/
It turns out to be a invalid json. What is wrong with the above json?
Upvotes: 0
Views: 138
Reputation: 572
The special characters need to escape according to the http://www.json.com. And you don't need to espace single-quote '
but It is a bad practice to use single-quote. For new readers, please use double-quote, It will let you get rid of many headaches.
\b Backspace (ASCII code 08)
\f Form feed (ASCII code 0C)
\n Newline
\r Carriage return
\t Tab
\" Double quote
\\ Backslash character
Todo:
Change single quote to double quote.
Apply the Characters given above to escape special characters.
Upvotes: 0
Reputation: 172
The quoted string on the right of "regex":
contains the character sequences
\. \w \] \+ \( \)
and each of these is not valid in a JSON string - See http://json.org/ for a brief and "visual" explanation of the grammar.
To represent the given regex as a valid JSON string, each backslash has to be doubled (i.e. replace \
by \\
, much like in other languages like PHP, C/C++ etc.), so the relevant line should become something like
"regex": "^(?:http(s)?:\\/\\/)?[\\w.-]+ ...
Upvotes: 1