I have a scenario where I need to validate whether the partial input(see below) is valid JSON or not? I have referred this answer to identify whether the given string is a valid JSON or not.
Example input:
{
"JSON": [{
"foo":"bar",
"details": {
"name":"bar",
"id":"bar",
What I have tried so far:
/ (?(DEFINE)
(?<number> -? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)? )
(?<boolean> true | false | null )
(?<string> " ([^"\n\r\t\\\\]* | \\\\ ["\\\\bfnrt\/] | \\\\ u [0-9a-f]{4} )* " )
(?<array> \[ (?: (?&json) (?: , (?&json) )* )? \s* \]{0,1} )
(?<pair> \s* (?&string) \s* : (?&json) )
(?<object> \{ (?: (?&pair) (?: , (?&pair) )* )? \s* \}{0,1} )
(?<json> \s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* )
) \A (?&json)\,{0,1} \Z /six
I made the closing of the array and objects optional(allow zero or one time). But there are some cases where this will fail, for example when you open a object without closing another object(shown below) the regex will still find a match.
Invalid, but still matches:
{
"JSON": [{
"foo":"bar",
"details": {
"name":"bar",
"id":"bar",{
How to validate the partial JSON input?
EDIT:
As mentioned by @ntahdh
in the comments, this regex won't work using the java.util.regex
. So now I need a regex which should work without recursion