user7915361
user7915361

Reputation: 19

How do I print the keyS from a json object using JQ

Sample input

{
 “event_timestamp”: “2016-03-16 13:19:53 UTC”,
 “query”: “Plagiarism”,
 “search_session_id”: “3605862756e95d26ac180",
 “version”: “0.0.2",
 “other”: “{\“client_timestamp\“:1458134393.932,\"ios_page_index\":3}“,
 “action”: “HIT_BOUNCE”
}

{
 “event_timestamp”: “2016-03-16 13:19:53 UTC”,
 “query”: “Plagiarism”,
 “search_session_id”: “3605862756e95d26ac180",
 “version”: “0.0.2",
 “other”:“{\“client_timestamp\“:1458134393.932,\"ios_page_index\":3,\"ios_index_path_row\":1}“,
 “action”: “HIT_BOUNCE”
}

I'd like to output the unique key name in "other" field

"client_timestamp,

ios_page_index,

ios_index_path_row "

Tried the following command but doesn't work so far

cat sampleexample.json | jq '.other|keys' | sort | uniq > other.json

Thanks in advance

Upvotes: 0

Views: 299

Answers (1)

peak
peak

Reputation: 116977

  1. The sample input is not JSON, which does not allow fancy quotes to be used as string delimiters. The following assumes the input has been corrected.

  2. The value of .other is a JSON string; you can use fromjson to change the string to a JSON object.

  3. sort|unique is redundant, as unique first sorts its input.

Putting it all together:

$ jq  '.other | fromjson | keys_unsorted | unique' input.json
[
  "client_timestamp",
  "ios_page_index"
]
[
  "client_timestamp",
  "ios_index_path_row",
  "ios_page_index"
]

(Using keys_unsorted saves one sort operation.)

Upvotes: 1

Related Questions