【问题标题】:mongodb / jsonpath / jmespath expression to filter object with properties that contain special or accented charactersmongodb / jsonpath / jmespath 表达式过滤具有包含特殊或重音字符的属性的对象
【发布时间】:2020-07-16 03:36:36
【问题描述】:

我需要过滤此 json 中包含特殊字符的对象。 (我可以写一个javascript或者在mongo中导入和查询数据。)

{
    "Detail": [{
            "name": "somename1",
            "text": "Sometext1"
        },
        {
            "name": "somename2",
            "text": "Sometext!"
        }, {
            "name": "somename3",
            "text": "método"
        }
    ]
}

预期输出

{
    "Detail": [
        {
            "name": "somename2",
            "text": "Sometext!"
        },
        {
            "name": "somename3",
            "text": "método"
        }
    ]
}

有没有办法在 jsonpath 或 jmspath 中使用正则表达式来做到这一点?

我尝试了各种方法来接近我需要的东西,比如这些,但我现在被阻止了

Detail[].text.contains(`é`) in jmespath

$.[?(@.text=~ ^[a-zA-Z0-9]*$].text in jsonpath

db.test.find({'Detail.text': /[a-zA-Z0-9]*$]/}) in mongodb where 'test' is the collection

【问题讨论】:

  • 谢谢@Joe,这有助于构建字符类,但我仍然无法弄清楚使用正则表达式过滤仅具有特殊字符属性的对象的语法。

标签: javascript json mongodb jsonpath jmespath


【解决方案1】:

我觉得你应该试试这个工具 Jayway JsonPath https://github.com/json-path/JsonPath

我在网上试了一下https://jsonpath.herokuapp.com/

在这张图片中你可以看到输出。

这是我使用的正则表达式

.Detail[?(@.text =~ /(?:^\W+\w*$)|(?:^\w+\W+$)|(?:^\w+\W+\w+$)/)]

我将问题分为三组

  1. 字符串以至少一个特殊字符或非单词字符 ^\W+ 开头,后跟零个或多个单词字符,即 $éxito

  2. 字符串以至少一个单词字符 ^\w+ 开头,后跟零个或多个非单词字符 \w* 即 culminó,knowledge。

  3. 字符串以至少一个单词字符 ^\w+ 开头,然后是一个或多个非单词字符 \W+,然后是至少一个单词字符,即 beneplácito、now|knowledge、what$$$$happen。

之前的每个案例都使用非捕获组 (?:) 进行分组,并且使用的逻辑运算是 OR (|),因为您的字符串可以匹配三个组中的任何一个。

我也用这个工具https://regexr.com/来准备正则表达式

顺便说一下,这是基于这个答案JsonPath expression to filter using regex

【讨论】:

  • 非常感谢。我无法弄清楚语法,但这有帮助。
猜你喜欢
  • 2018-10-19
  • 1970-01-01
  • 2012-10-08
相关资源
最近更新 更多