使用字符串过滤JMESPath

问题描述 投票:0回答:1

尽管进行了大量研究,但我找不到解决方案。我坚持包含功能。我有这个Json文件:

    {
  "from": "Api",
  "success": true,
  "message": "",
  "errors": [],
  "data": {
    "operations": [
      {
        "IDOperation": 100,
        "DateEcriture": "2019-01-02",
        "Comment": "Invoice Nh5 numero 152",
        "sous_operations": []
      },
      {
        "IDOperation": 101,
        "DateEcriture": "2019-01-02",
        "Comment": "one other thing",
        "sous_operations": []
      },
      {
        "IDOperation":102,
        "DateEcriture": "2019-01-02",
        "Comment": "an other thing",
        "sous_operations": [{"ID-sous-Operation": 103,
                           "DateEcriture": "2019-01-02",
                           "Comment": "Invoice Nh15 numero 341"}]
      }]
   } 
}

而且我想在“注释”字段中过滤带有“发票”一词的对象以获取此信息:

{"operations": [
      {
        "IDOperation": 100,
        "DateEcriture": "2019-01-02",
        "Comment": "Invoice Nh5 numero 152"
      },
      {
        "IDOperation": 103,
        "DateEcriture": "2019-01-02",
        "Comment": "Invoice Nh15 numero 341"
      }]
}

感谢您的帮助

json search substring contains jmespath
1个回答
0
投票
您尚未说明遇到困难的部分。我猜想它正在处理嵌套的子操作,因为这对我来说似乎是最困难,最不明显的部分,但是我会尽力介绍所有内容。

这是我的假设:

    输入始终由具有字段data的对象组成。
  • [data字段始终是具有字段operations的对象。
  • operations始终是数组。
  • operations的每个成员都具有相同的四个字段:IDOperationDateEcritureCommentsous_operations
  • sous_operations始终是数组。
  • sous_operations的每个成员都具有相同的三个字段:ID-sous-Operation(!),DateEcritureComment
  • 尤其是子操作嵌套的深度不超过一层。
  • 所有名为Comment的字段都是字符串。
  • 您想查找在Comment字段中具有“发票”(不区分大小写)的工序和子工序。
  • 您要输出它们,但不输出它们可能具有的任何子操作。
  • 您要将ID-sous-Operation重命名为IDOperation
  • 输出应包含一个包含单个字段operations的对象,该字段是所选操作和转换操作的数组。
  • 我认为这可以满足您的要求:

    { operations: data.operations| map( &[ [ { IDOperation:IDOperation, DateEcriture:DateEcriture, Comment:Comment } ], map( &{ IDOperation:"ID-sous-Operation", DateEcriture:DateEcriture, Comment:Comment }, sous_operations ) ], @ )| [][]| [?contains(Comment,`"Invoice"`)] }

    首先,我们将每个操作替换为两个成员的数组。第一个成员是单个元素数组,其中包含操作的字段,但不包含其子操作。第二个成员是所有操作的子操作的数组。 (这时,我们还重命名了子操作ID字段。)

    所以现在我们将操作作为简化操作数组的(两个元素)数组的数组。我们两次使用flatten运算符来获得一个简单的单级数组。最后,我们仅使用contains方法对其进行过滤。

    这是输出:

    $ jp --filename input1.json --expr-file filter.jmespath { "operations": [ { "Comment": "Invoice Nh5 numero 152", "DateEcriture": "2019-01-02", "IDOperation": 100 }, { "Comment": "Invoice Nh15 numero 341", "DateEcriture": "2019-01-02", "IDOperation": 103 } ] }

  • © www.soinside.com 2019 - 2024. All rights reserved.