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 :))
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.
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'sfrom_entries, which reverses this operation.with_entries(f)is, if I recall correctly, the same asto_entries | map(f) | from_entries.So then I'm assigning the
.valueof each of these objects (which are representations of key-value pairs of objects) to itself piped through thetypefunction. 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.