简体   繁体   中英

Find object in JSON with RegExp

I have a JSON string and need to find an nested object and only want the object matching my regexp returned.

{
  "some": {
    "nested": {
       "stuff": [
         {
           "bla": "blub1",
           "bar": "bar"
         },
         {
           "bla": "blub2",
           "bar": "foo"
         },
         {
           "bla": "blub3",
           "bar": "foobar"
         }
      ]
   }
}

I almost got it with this reg exp /{(.*?"bar": "foo".*?)}/gs but this does not return only the matching object.

I only want it to return this:

{
    "bla": "blub2",
    "bar": "foo"
}

See: https://regex101.com/r/mK3oI6/3

I actually don't want to use regex but I'm trying to find the best solution to find a object in a nested object and thought it might work good with regex.

EDIT: I unterstand that this is not a good approach but I just want to try and see the performance between regex and parsing the JSON and and make a deep search

If you are deadset on using regex:

[^{]*?({\\s+"bla[^}]*?})

basically, does a non greedy search until the first { <space> "bar , captures until the first closing curly brace.

edit: if you want only the Nth instance, [^{]*?(?:{\\s+"bla[^}]*?}){N}[^{]*?({\\s+"bla[^}]*?})

if you want only the one with bar : foo:

.*{([^}]*bar.*?foo"[^}]*?)}

USING JSON WITH REGEX IS A BAD IDEA. becomes fickle and could break easily. It would be a better idea to use one of the primitive iterable types, load the json using the json library, and simply index your way through it to get the data you want.

You are putting the parenthesis in the wrong positions, this way you are capturing everything till you find your match

if you do {.*("bar": "foo").*}

it will just return the matching part (but it is a greedy search, careful with the size)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM