Jq: Show property name and type

Created on 2 May 2014  路  4Comments  路  Source: stedolan/jq

Hi,

I'm trying to list all properties and their types for an object. The closest I've been able to get so far is with something like this:

cat file.json | jq '.property | keys, map(type)'

I end up with two arrays; the first listing the property names, the second listing types. Is there a way I can interleave each key and its type? Ultimately, I'd like to end up with a new object containing the original object's keys and with their types as their values. So, if started with something like this:

{
  "myStringProperty": "this is a string",
  "myArrayProperty": [ 1, 2, 3 ]
}

I would end up with something like this:

{
  "myStringProperty": "string",
  "myArrayProperty": "array",
 ...
}

Note that I don't need to recurse into other objects (not yet :))

support

Most helpful comment

Okay, so from the top of my head, there's to_entries, which turns {"foo": "bar"} into [{"key": "foo", "value": "bar"}], and there's from_entries, which reverses this operation. with_entries(f) is, if I recall correctly, the same as to_entries | map(f) | from_entries.

So then I'm assigning the .value of each of these objects (which are representations of key-value pairs of objects) to itself piped through the type function. Actually, while explaining this, I realized there's a much more cleaner way to do this: the jq manual talks about the pipe assignment operator, which does exactly what we need to. We can substitute the above code with the following one using said operator:

jq 'with_entries(.value |= type)'

You can read more on the subject on jq manual's pages on assignment and with_entries.

All 4 comments

jq 'with_entries(.value = (.value | type))' should do the work.

Works great. Thanks! Now I have to study this to understand how this works :)

Okay, so from the top of my head, there's to_entries, which turns {"foo": "bar"} into [{"key": "foo", "value": "bar"}], and there's from_entries, which reverses this operation. with_entries(f) is, if I recall correctly, the same as to_entries | map(f) | from_entries.

So then I'm assigning the .value of each of these objects (which are representations of key-value pairs of objects) to itself piped through the type function. Actually, while explaining this, I realized there's a much more cleaner way to do this: the jq manual talks about the pipe assignment operator, which does exactly what we need to. We can substitute the above code with the following one using said operator:

jq 'with_entries(.value |= type)'

You can read more on the subject on jq manual's pages on assignment and with_entries.

Thanks for the explanation. The |= version works as well.

Was this page helpful?
0 / 5 - 0 ratings