Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get keys in JSON

Tags:

json

jsonpath

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?

like image 428
Stefan Avatar asked Sep 28 '17 14:09

Stefan


People also ask

How do I get the key of a JSON object?

To get key and value from json object in javascript, you can use Object. keys() , Object. values() , for Object. entries() method the methods helps you to get both key and value from json object.

What is key-value in JSON?

A JSON object contains zero, one, or more key-value pairs, also called properties. The object is surrounded by curly braces {} . Every key-value pair is separated by a comma. The order of the key-value pair is irrelevant. A key-value pair consists of a key and a value, separated by a colon ( : ).

How can I get specific data from JSON?

Getting a specific property from a JSON response object Instead, you select the exact property you want and pull that out through dot notation. The dot ( . ) after response (the name of the JSON payload, as defined arbitrarily in the jQuery AJAX function) is how you access the values you want from the JSON object.


1 Answers

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.

like image 115
Viktor Avatar answered Oct 18 '22 06:10

Viktor