我目前正在开发一个从另一位开发人员那里继承的项目,该项目广泛使用 JSONPATH 来解析 JavaScript 对象。
作为一个 Nodejs 项目,我发现 JSONPATH 的使用令人困惑,而不是具有启发性。
只要我发现它有利于简单的映射、过滤器、归约等,我就会系统地从项目中删除它,因为它们使我更容易理解代码。但在我 promise 完全删除它之前,我想知道是否有任何我可能错过的优势。我也承认我对此有些不情愿,因为我以前从未遇到过。
我认为 JSONPATH 在以下情况下会非常有用: A) 你不确定你得到的 json 数据的结构, B)您正在解析深度嵌套的对象,您可能还需要展平或 C) 您正在使用 JavaScript 以外的语言。
但我认为这不适用于我的项目。我还有什么遗漏的吗?
最佳答案
当您的系统需要大量操作 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. |
+---------------------------------------+--------------------------------------------------------------+
一旦您开始使用 JSONpath,您就会了解它为您提供的灵 active 和实用性。节省您的时间和代码空间。
关于javascript - JSONPATH 有什么优点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44786285/