Home > Net >  How to get root elements contains specific character
How to get root elements contains specific character

Time:12-31

I have a json file and want to extract all root elements contains a specific character in array.

My json file structure:

{
"12": [
    "12",
    "200 OK",
    "{\r\n  \"ResponseText\": null,\r\n  \"RegistrationUserID\": {}\r\n}"
],
"19": [
    "23",
    "200 OK",
    "{\r\n  \"ResponseText\": null,\r\n  \"RegistrationUserID\": {\r\n    \"1\": \"2019***091\",\r\n    \"2\": \"2019****67\"\r\n  }\r\n}"
],
"20": [
    "434",
    "200 OK",
    "{\r\n  \"ResponseText\": null,\r\n  \"RegistrationUserID\": {\r\n    \"1\": \"2019****83\"\r\n  }\r\n}"
],
"333": [
    "25",
    "200 OK",
    "{\r\n  \"ResponseText\": null,\r\n  \"RegistrationUserID\": {\r\n    \"1\": \"2019****32\"\r\n  }\r\n}"
],
"3454": [
    "55",
    "200 OK",
    "{\r\n  \"ResponseText\": null,\r\n  \"RegistrationUserID\": {\r\n    \"1\": \"2019****1\"\r\n  }\r\n}"
],
"23": [
    "66",
    "200 OK",
    "{\r\n  \"ResponseText\": null,\r\n  \"RegistrationUserID\": {\r\n    \"1\": \"2019****5\"\r\n  }\r\n}"
],
"23424": [
    "34",
    "200 OK",
    "{\r\n  \"ResponseText\": null,\r\n  \"RegistrationUserID\": {\r\n    \"1\": \"2019****2\"\r\n  }\r\n}"
],

}

I want to extract all root values contains "***" on them.

Result should looks:

19 20 333 3454 23 23424

How can I parse my json file using JQ to extract target root elements?

CodePudding user response:

@peak's solution is the right answer to the question asked. However, if you want to dive into the encoded JSON contained within the top arrays' third elements and search just in them instead, use the fromjson builtin:

to_entries[]
| select(any(.value[2] | fromjson | .RegistrationUserID[]; test("\\*\\*\\*")))
| .key
19
20
333
3454
23
23424

Demo

CodePudding user response:

When the extraneous comma is removed from the JSON, and when the -r command-line option is used, the filter:

to_entries[]
| select( any(.value[]; test("\\*\\*\\*") ))
| .key

produces the stream:

19
20
333
3454
23
23424

You can easily package these values any way you want, e.g. using jq itself.

  • Related