简体   繁体   English

使用RegExp在JSON中查找对象

[英]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. 我有一个JSON字符串,需要找到一个嵌套的对象,只希望返回与我的正则表达式匹配的对象。

{
  "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. 我几乎可以通过此reg exp /{(.*?"bar": "foo".*?)}/gs获得它,但这并不只返回匹配的对象。

I only want it to return this: 我只希望它返回此:

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

See: https://regex101.com/r/mK3oI6/3 参见: 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 编辑:我不明白这不是一个很好的方法,但我只想尝试看看正则表达式和解析JSON之间的性能,并进行深度搜索

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. 基本上,会进行非贪婪搜索,直到第一个{ <space> "bar捕获到第一个闭合花括号为止。

edit: if you want only the Nth instance, [^{]*?(?:{\\s+"bla[^}]*?}){N}[^{]*?({\\s+"bla[^}]*?}) 编辑:如果只需要第N个实例,则[^{]*?(?:{\\s+"bla[^}]*?}){N}[^{]*?({\\s+"bla[^}]*?})

if you want only the one with bar : foo: 如果只想要带有bar的那个:foo:

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

USING JSON WITH REGEX IS A BAD IDEA. 将JSON与REGEX一起使用是一个糟糕的想法。 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. 最好使用一种原始的可迭代类型,使用json库加载json,然后简单地对它进行索引以获取所需的数据。

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").*} 如果您执行{.*("bar": "foo").*}

it will just return the matching part (but it is a greedy search, careful with the size) 它只会返回匹配的部分(但这是一个贪婪的搜索,请注意大小)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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