JSONPATH的优点是什么?

时间:2017-06-27 17:19:52

标签: javascript jsonpath

我目前正在开发一个项目,我继承自另一个开发人员,该项目广泛使用JSONPATH来解析JavaScript对象。

作为一个nodejs项目,我发现使用JSONPATH是混淆而不是启发。

每当我发现它支持简单的地图,过滤器,缩小等时,我一直在系统地将其从项目中移除,因为它们使代码更容易让我理解。但是在我承诺完全删除之前我想知道,如果有任何优势我可能会失踪。我也承认不喜欢它,因为我以前从未遇到它。

我假设JSONPATH在以下情况下非常有用: A)你不确定你得到的json数据的结构, B)您正在解析您可能还需要展平的DEEPLY嵌套对象 C)您正在使用JavaScript之外的其他语言。

但我觉得这不适用于我的项目。还有其他我想念的东西吗?

1 个答案:

答案 0 :(得分:0)

当您的系统需要大量操作json字符串并从中获取/过滤必要的数据时,JSONpath成为一个优势。我们可以避免编写长循环和嵌套循环,以便遍历json对象和json数组。如果您正在开发系统的语言具有JSONpath支持,那么我的建议是随时随地使用它。

此处演示了示例用法。

让我们说你的json就像下面一样。

{ "store": {
         "book": [ 
          { "category": "reference",
             "author": "Nigel Rees",
             "title": "Sayings of the Century",
             "price": 8.95
          },
          { "category": "fiction",
            "author": "Evelyn Waugh",
            "title": "Sword of Honour",
            "price": 12.99
          },
          { "category": "fiction",
            "author": "Herman Melville",
            "title": "Moby Dick",
            "isbn": "0-553-21311-3",
            "price": 8.99
          },
          { "category": "fiction",
            "author": "J. R. R. Tolkien",
            "title": "The Lord of the Rings",
            "isbn": "0-395-19395-8",
            "price": 22.99
           }
         ],
        "bicycle": {
           "color": "red",
           "price": 19.95
         }
      }
    }

这是一种可以从json中操作和获取细节的方法。

+---------------------------------------+--------------------------------------------------------------+
|               JSONPath                |                            Result                            |
+---------------------------------------+--------------------------------------------------------------+
| $.store.book[*].author                | the authors of all books in the store                        |
| $..author                             | all authors                                                  |
| $.store.*                             | all things in store, which are some books and a red bicycle. |
| $.store..price                        | the price of everything in the store.                        |
| $..book[2]                            | the third book                                               |
| $..book[(@.length-1)] or $..book[-1:] | the last book in order.                                      |
| $..book[0,1] or $..book[:2]           | the first two books                                          |
| $..book[?(@.isbn)]                    | filter all books with isbn number                            |
| $..book[?(@.price<10)]                | filter all books cheapier than 10                            |
| $..*                                  | all Elements in XML document. All members of JSON structure. |
+---------------------------------------+--------------------------------------------------------------+

一旦开始使用JSON路径,您将了解它为您提供的灵活性和实用性。节省您的时间和代码空间。