【问题标题】:How to find unpredictable parent of specific child in JSON using regexp?如何使用正则表达式在 JSON 中查找特定子项的不可预测父项?
【发布时间】:2022-01-22 08:44:29
【问题描述】:

在下面的 JSON 中,如何使用正则表达式匹配名为“Item of Equipment”的父键,其值在变化且不可预测?

"type": "title" 是该节点独有的,"title:" 的存在也是如此。

又名:“如何使用子元素匹配父值?

找到“Item of Equipment”的另一种方法是在属性“name”中查找它,它是重复的,作为"type": "title 的同级。在这种情况下,"type": "title" 始终具有唯一性“name”的兄弟

    ..
    "id": "Xkt@",
    "name": "My Email",
    "type": "email"
  },
  "Item of Equipment": {
    "id": "title",
    "title": {},
    "name": "Item of Equipment",
    "type": "title"
  },
  "My Date": {
    "id": "nYcK",
    "name": "My Date",
    "type": "date",
    ..

我不会使用 JSON 解析器,我将无权访问。我正在通过 iOS Shortcuts 的“匹配”操作来运行它。

【问题讨论】:

标签: json regex


【解决方案1】:

注意事项

  1. 基于JSON validation via RegEx
  2. 添加“原子组”以避免回溯。
  3. 假设 iOS“匹配”使用类似于 Perl 的正则表达式 (ICU)。
  4. 如果需要单行正则表达式,则留给读者练习。
  5. 注意大型 JSON 输入的性能/可用性可能会导致正则表达式引擎出现问题(“您的里程可能会有所不同”)。

正则表达式

(?(DEFINE)
     (?<number>   (?>-? (?= [1-9]|0(?!\d) ) \d+ (\.\d+)? ([eE] [+-]? \d+)?) )
     (?<boolean>   (?> true | false | null ))
     (?<unquoted>  (?>  ([^"\\]* | \\ ["\\bfnrt\/] | \\ u [0-9a-f]{4} )* ))
     (?<string>    (?>" (?&unquoted) " ))
     (?<array>     (?> \[  (?:  (?&json)  (?: , (?&json)  )*  )?  \s* \] ))
     (?<pair>      (?> \s* (?&string) \s* : (?&json)  ))
     (?<object>    (?>\{  (?:  (?&pair)  (?: , (?&pair)  )*  )?  \s* \} ))
     (?<json>   (?>\s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) \s* ))
  )
(?<=")           # Lookbehind for quote before parent key string
(?&unquoted)     # parent key string 
(?=              # Lookahead for object properties including unique property marker
"\s*:\s*{\s*
(?:  (?&pair)  (?: , (?&pair)  )*  )?    # any number of property key value pairs, optional.
(?:(?:\s* , )?\s* "type"\s*:\s*"title")  # unique property marker, optionally perfixed with comma.
(?: \s*, (?&pair)  )*                    # any number of property key value pairs, optional.
\s*}
)

证明

https://regex101.com/r/kN74Th/1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多