I am looking for a Regex that allows me to validate json.
I am very new to Regex\'s and i know enough that parsing with Regex is bad but can it be used to validate?
Looking at the documentation for JSON, it seems that the regex can simply be three parts if the goal is just to check for fitness:
[]
or {}
[{\[]{1}
...[}\]]{1}
[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]
...""
".*?"
...All together:
[{\[]{1}([,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]|".*?")+[}\]]{1}
If the JSON string contains newline
characters, then you should use the singleline
switch on your regex flavor so that .
matches newline
. Please note that this will not fail on all bad JSON, but it will fail if the basic JSON structure is invalid, which is a straight-forward way to do a basic sanity validation before passing it to a parser.