Get keys in JSON

╄→гoц情女王★ 提交于 2019-12-10 13:38:00

问题


I get the following JSON result from an external system:

{
  "key1": "val1",
  "key2": "val2",
  "key3": "val3"
}

Now I want to display all keys and all values by using JSONPath. So I am looking for something to get key1, key2 and key3 as a result. Additionally I would like to use the index of a property, e. g. $....[2].key to get "key3" etc. Is there a way to do something like this?


回答1:


I found that the tilda ~ symbol is able to retrieve the keys of the values it's called upon. So for your example a query like this:

$.*~

Returns this:

[
  "key1",
  "key2",
  "key3"
]

Another example, if we had a JSON document like this:

  {
  "key1": "val1",
  "key2": "val2",
  "key3": {
      "key31":"val31",
      "key32":"val32"
  }
}

A query like this:

$.key3.*~

Would return this:

[
  "key31",
  "key32"
]

It's important to note that these examples work on JSONPath.com and some other simulators/online tools, but on some they don't. It might come from the fact that I found out about the tilda(~) operator in the JSONPath plus documentation and not the official one.



来源:https://stackoverflow.com/questions/46471516/get-keys-in-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!