Search code examples
regexjsonvimvi

Vim regex to find missing JSON element


I have a big JSON file, formatted over multiple lines. I want to find objects that don't have a given property. The objects are guaranteed not to contain any further nested objects. Say the given property was "bad", then I would want to locate the value of"foo" in the second element in the following (but not in the first element).

{
  result: [
    {
      "foo" : {
        "good" : 1,
        "bad" : 0
      },
      "bar" : 123
    },
    {
      "foo" : {
        "good" : 1
      },
      "bar" : 123
    }
  ]
}

I know about multi-line regexes in Vim but I can't get anything that does what I want. Any pointers?


Solution

  • Try the following:

    /\v"foo"\_s*:\_s*\{%(%(\_[\t ,]"bad"\_s*:)@!\_.){-}\}
    

    When you need to exclude something, you should look at negative look-aheads or look-behinds (latter is slower and unlike vim Perl/PCRE regular expressions do not support look-behinds except fixed-width (or a number of alternative fixed-width) ones).