Home > Net >  JQ Diagnostic, getting paths with types
JQ Diagnostic, getting paths with types

Time:12-02

I'm trying to get JQ script running, that will help me find all possible path and the type the path offers.

Thus far, let's say I have this JSON

          {
              "_links": {
                  "self": {
                      "href": "HTTPS",
                      "type": "application/json"
                  }
              },
              "items": [
                  {
                      "_links": {
                          "parent": {
                              "href": "LINK",
                              "type": "application/json"
                          },
                          "self": {
                              "href": "LINK",
                              "type": "application/json"
                          }
                      },
                      "_maintainer": {
                          "_id": 1,
                          "email": "EMAIL",
                          "value": true
                      }
                  }
              ],
              "totalCount": 1
          }

And I have managed to put together a JQ query, that

select(objects)|=[.] 
    | map( paths(scalars) ) 
    | 
        map(
            map(select(numbers)="[]") 
            | join(".")
        ) 
    | unique

That does give me paths to all the properties in the JSON.

[
  "_links.self.href",
  "_links.self.type",
  "items.[]._links.parent.href",
  "items.[]._links.parent.type",
  "items.[]._links.self.href",
  "items.[]._links.self.type",
  "items.[]._maintainer._id",
  "items.[]._maintainer.email",
  "items.[]._maintainer.value",
  "totalCount"
]

But this is only half a journey. I watned to get an output, where each path also shows what type it is.

That does give me paths to all the properties in the JSON.

[
  { "_links.self.href": "string" },
  ...
  { "items.[]._maintainer.value": "boolean" },
  { "totalCount": "number" }
]

Now, I know that JQ can do typeof or | type, but when adding it to the query after | unique it of course fails.

What way should I structure the query, for this to be able to achieve?

CodePudding user response:

Using paths

[
  paths(scalars) as $p
  | {($p | map(numbers = "[]") | join(".")): getpath($p) | type}
]
| unique

Demo

Using tostream

reduce (tostream | select(has(1))) as [$p, $v] ([]; .   [{
  ($p | map(numbers = "[]") | join(".")): ($v | type)
}])
| unique

Demo

Output:

[
  {"_links.self.href":"string"},
  {"_links.self.type":"string"},
  {"items.[]._links.parent.href":"string"},
  {"items.[]._links.parent.type":"string"},
  {"items.[]._links.self.href":"string"},
  {"items.[]._links.self.type":"string"},
  {"items.[]._maintainer._id":"number"},
  {"items.[]._maintainer.email":"string"},
  {"items.[]._maintainer.value":"boolean"},
  {"totalCount":"number"}
]
  • Related