Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping Regex to get Valid JSON

Tags:

json

schema

In my schema, I want to recognize certain patterns to restrict the type of data that a user can enter. I use regex to restrict what a user can enter, but the regex get flagged when I try to validate the JSON using an online validator like this one.

Is there a way to make the validator ignore the regex special chars that are disagreeing with it, but still keep the regex?

The weird thing is that the validator only trips up on certain instances. For instance, it flags the second and not the first instance of regex despite them being identical here:

            "institutionname": {                 "type": "string",                 "description": "institution name",                 "label": "name",                 "input-type": "text",                 "pattern": "^[A-Za-z0-9\s]+$"             },             "bio": {                 "type": "string",                 "label": "bio",                 "input-type": "text",                 "pattern": "^[A-Za-z0-9\s]+$",                 "help-box": "tell us about yourself"             }, 
like image 364
goldisfine Avatar asked Jul 11 '13 15:07

goldisfine


People also ask

Is regex valid JSON?

Yes, a complete regex validation is possible. Most modern regex implementations allow for recursive regexpressions, which can verify a complete JSON serialized structure.

How do I check if JSON is valid?

In order to check the validity of a string whether it is a JSON string or not, We're using the JSON. parse()method with few variations. This method parses a JSON string, constructs the JavaScript value or object specified by the string.

Can JSON be parsed with regex?

With this information, it is possible to use regex to filter a JSON object to return the key, the value, and the parent object chain.


2 Answers

Its just the slashes that are messing up the validation you could encode them using %5C which is the hex encoding of \ or what Mike W says you could double escape like \\ and then you could just decode them when you want to use them

like image 152
Legion Avatar answered Nov 10 '22 05:11

Legion


The accepted answer doesn't work for me. %5C doesn't work well with a linter. Plus manually doing it is a job. How about a very long regex -

^(([^<>()[\\]\\.,;:\\s@\"]+(\\.[^<>()[\]\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$

So, please don't kill yourself and head to this get this done - https://www.freeformatter.com/json-escape.html#ad-output

In case the link doesn't work in future, please find some other online tool :)

like image 32
HalfWebDev Avatar answered Nov 10 '22 06:11

HalfWebDev