1

I need to find all JSON strings in a document.

  • I am OK with an assumption that all strings that start with { are JSON.
  • I am OK with an assumption that the JSON can be invalid.
Gajus
  • 69,002
  • 70
  • 275
  • 438

1 Answers1

2

This is a regular expression solution:

{
    (?>
        "(?>\\.|[^"])*"|
        [^{}"]+|
        (?R)
    )*
}

This will capture a JSON structure that can have infinite nesting, e.g.

{
    "foo": "bar",
    "foo": false,
    "foo": 123,
    {
        "foo": "bar"
    },
    "foo": "}}}"
}

I have setup a regex101 playground if you have a test case of your own or need an explanation of the expression.

Unfortunately, JavaScript does not provide the PCRE recursive parameter (?R). XRegExp is an open source JavaScript library that provides augmented regular experssions, including support for recursive matching.

Community
  • 1
  • 1
Gajus
  • 69,002
  • 70
  • 275
  • 438