23

我正在使用带有jsonpath的nodejs。我有这个json结构:

{
  things:{
    books: [
      {name: "book1"},
      {name: "book2"},
      {name: "book3"},
      {name: "book4"},
    ],
    movies: [
      {name: "movie1"},
      {name: "movie2"},
      {name: "movie3"},
      {name: "movie4"},
    ]
  }
}

我想知道返回带有things对象键名的数组的 jsonpath 表达式。那将是:

["books","movies"]

现在,我正在这样做:

Object.keys(jsonpath.eval(jsonStructure,"$.things").pop());

但我不觉得它很优雅......当我只需要键名时,我不需要获取整个结构的副本。

4

4 回答 4

7

jsonPath 有新的更新 jsonpath-plus jsonpath-plus 扩展了原始规范,添加了一些额外的操作符,并明确了一些原始规范没有说明的行为。

^获取匹配项的父项 ~获取匹配项的属性名称(作为数组)

因此要获得正确的输出,请使用此查询things.*~ ,您也可以在此处尝试https://jsonpath.com/

于 2019-11-20T17:11:08.247 回答
2

我不相信有比你自己更好的解决方案:

Object.keys(jsonpath.eval(jsonStructure,"$.things").pop());

我认为这里的主要误解是您不必担心这个片段“获取整个结构的副本”,因为您没有复制整个结构。您已经将整个对象加载到内存中,jsonpath 不会创建新副本,它只是返回对现有对象的引用,即:

jsonpath.eval(jsonStructure,"$.things").pop() === jsonStructure.things //true
于 2014-05-19T23:44:02.173 回答
1

Not exactly what you are asking for, but might still be relevant.

We use object-scan for this kind of task as it is much better suited for data processing and analyzing. Once you wrap your head around it that is (:

Anyways, here is how you could answer your question if you are willing to add another dependency

// const objectScan = require('object-scan');

const data = { things: { books: [ { name: 'book1' }, { name: 'book2' }, { name: 'book3' }, { name: 'book4' } ], movies: [ { name: 'movie1' }, { name: 'movie2' }, { name: 'movie3' }, { name: 'movie4' } ] } };

console.log(objectScan(['things.*'], { rtn: 'property' })(data));
// => [ 'movies', 'books' ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.7.1"></script>

Disclaimer: I'm the author of object-scan

于 2020-11-18T02:01:27.603 回答
-1

您用于 give 的语法是错误的,无法在 json 路径中使用"$.*~" ex 获取键。 输入:{“firstName”:“John”、“lastName”:“doe”、“age”:26 } 输出:[“firstName”、“lastName”、“age”]

于 2021-01-15T15:27:42.470 回答