YXD
YXD

Reputation: 32511

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?

Upvotes: 2

Views: 694

Answers (3)

Alan Gómez
Alan Gómez

Reputation: 378

The simplest way to do that is:

/\(foo\_.\{-}bad\)\@!foo

Best regards!

Upvotes: 0

ZyX
ZyX

Reputation: 53604

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).

Upvotes: 4

Andrew White
Andrew White

Reputation: 53496

JSON is a context free grammar and as such is not regular. Unless you can give a much stricter set of rules to go on, no regex will be able to do what you want.

Upvotes: 1

Related Questions