Evaluating command inside JQ pipeline - jq

I'm struggling evaluating a command inside a jq pipeline. Example will make it easier. Let's imagine I've got this simple json
{
"model": [{
"id": "an-id",
"path": [
"mypath1.txt"
],
"model": "foo"
},
{
"id": "an-id2",
"path": [
"mypath1.txt"
],
"model": "foo2"
}
]
}
And I want to convert into this
{
"model": [{
"id": "an-id",
"path": [
"mypath1.txt"
],
"model": "foo",
"alternative_model": "I am a computed value out of <foo>"
},
{
"id": "an-id2",
"path": [
"mypath1.txt"
],
"model": "foo2",
"alternative_model": "I am a computed value out of <foo2>"
}
]
}
I want to do something like this that allows me to delegate computing alternative model to a different bash script.
myNewJson=$(cat mappings.json | jq '[.model[]| {
id: .id,
path: .path
model: .model
alternative_model: //TODO}' ---> here I'd like to do something like "eval ./myscript $model"
])
Thanks!

Let's assume myscript contains following line :
echo "I am a computed value out of <$1>"
As jq does not allow to evaluate shell commands, you need something like :
#!/usr/bin/env bash
input=mappings.json
alternative-models(){
local result='{}' sres
for id in $(jq -r '.model[].id' $input); do
model="$(jq -r --arg id "$id" '.model[]|select(.id==$id).model' $input)"
amodel="$(./myscript $model)"
result="$(jq --arg id $id --arg amodel "$amodel" '. + { $id: $amodel }' <<< "$result")"
done
echo "$result"
}
jq --argjson amodels "$(alternative-models)" '.model|map({
id, path, model, "alternative_model": $amodels[.id] }
)' $input
Your mappings.json is not valid json because of a comma on the model line.

Related

get all folder-ids in my account in Nebius cloud?

Using nebius-cloud-cli I am trying to list only name and id of all folders in my account.
I tried this:
yc vpc networks list --format json | jq ".[] "
The output I got was:
{
"id": "ccm979ujel7gpcq6aulc",
"folder_id": "b489aa1fe17nphuomth8",
"created_at": "2022-12-12T17:47:24Z",
"name": "default",
"description": "Auto-created network"
}
{
"id": "ccmn8qvg1uaaaiblc05e",
"folder_id": "b4aaav1fe1gnphuomth8",
"created_at": "2022-12-29T12:07:40Z",
"name": "my-network"
}
{
"id": "campid2asepq3bc68fn6",
"folder_id": "b489kv3ae1ga1huomth8",
"created_at": "2021-12-18T09:54:01Z",
"name": "my-nw",
"description": "Auto-created network"
}
Expected output:
[
{"name": "default",
"folder_id": "b4aaav1fe1gnphuomth8"
},
{"name": my-nw,
"folder_id": "b489kv3ae1ga1huomth8"
}
]
Try it out
The output I got is a multi line non standard JSON coming from this output, and needs to be handled correctly.
I'm looking for a simple transformation, not redirection and awks and stuff like this << in bash which defeats the purpose.
Use map({ name, folder_id }) with --slurp:
command | jq --slurp 'map({ name, folder_id })'
--slurp
Instead of running the filter for each JSON object in the input, read the entire input stream into a large array and run the filter just once.
Documentation
Input:
{
"id": "ccm979ujel7gpcq6aulc",
"folder_id": "b489aa1fe17nphuomth8",
"created_at": "2022-12-12T17:47:24Z",
"name": "default",
"description": "Auto-created network"
}
{
"id": "ccmn8qvg1uaaaiblc05e",
"folder_id": "b4aaav1fe1gnphuomth8",
"created_at": "2022-12-29T12:07:40Z",
"name": "my-network"
}
{
"id": "campid2asepq3bc68fn6",
"folder_id": "b489kv3ae1ga1huomth8",
"created_at": "2021-12-18T09:54:01Z",
"name": "my-nw",
"description": "Auto-created network"
}
Output
[
{
"name": "default",
"folder_id": "b489aa1fe17nphuomth8"
},
{
"name": "my-network",
"folder_id": "b4aaav1fe1gnphuomth8"
},
{
"name": "my-nw",
"folder_id": "b489kv3ae1ga1huomth8"
}
]
Demo
JqPlay Demo
Since you use .[] in your question, this makes me think the output of the command is an array. Use map to apply a transformation to each item in the array:
$ yc ...
[
{...},
{...}
]
$ yc ... | jq 'map({ name, folder_id })'
[
{...},
{...}
]
.[] streams all items of an array. To transform the stream, use the object construction without map:
$ yc ...
[
{...},
{...}
]
$ yc ... | jq '.[] | { name, folder_id }'
{...}
{...}
Or if yc outputs multiple JSON objects, then don't stream and transform directly:
$ yc ...
{...}
{...}
$ yc ... | jq '{ name, folder_id }'
{...}
{...}
If the output of yc is actually a single object with multiple properties, you can still use map like with a regular array; it will automatically return the properties' values only:
$ yc ...
{
"a": {...},
"b": {...}
}
$ yc ... | jq 'map({ name, folder_id })'
[
{...},
{...}
]
If yc outputs multiple JSON objects and you need the output to be an array, then slurp the input with -s/--slurp into one big array and then apply the map operation:
$ yc ...
{...}
{...}
$ yc ... | jq -s 'map({ name, folder_id })'
[
{...},
{...}
]
Assuming calling yc vpc networks list --format json just by itself produces something structured like
{
"networks": [
{
"id": "4e8a4034-a973-4f1f-84a8-73ea54adcee1",
"name": "my-network",
"description": "My network",
"created_at": "2022-01-01T00:00:00Z",
"folder_id": "b1g7f0d3-2e0a-4714-ba6a-b1g7f0d32e0a",
"vpc_id": "b1g7f0d3-2e0a-4714-ba6a-b1g7f0d32e0a",
"region_id": "ru-central1"
}
]
}
Then piping this into jq '.networks | map({name, folder_id})' would give you
[
{
"name": "my-network",
"folder_id": "b1g7f0d3-2e0a-4714-ba6a-b1g7f0d32e0a"
}
]
Demo

How to get value pairs of the objects from JSON using jq

I have a json file named as param.json that looks as below:
[
{
"Value": "anshuman.ceg+Dev#gmail.com",
"Key": "AccountEmail"
},
{
"Value": "DevABC",
"Key": "AccountName"
},
{
"Value": "Security (ou-nzx5-8ajd1561)",
"Key": "ManagedOrganizationalUnit"
},
{
"Value": "anshuman.ceg+Dev#gmail.com",
"Key": "SSOUserEmail"
},
{
"Value": "John",
"Key": "SSOUserFirstName"
},
{
"Value": "Smith",
"Key": "SSOUserLastName"
}
]
I want to get only the Value for DevABC so that I can use while reading the -r line. I need only DevABC
I am using jq as follows which doesn't seem to work
jq -r .[1].Value param.json
Assuming all your Key values are distinct, you can first convert the array into an object and then access the "AccountName" property directly:
jq -r 'from_entries | .AccountName' param.json
from_entries will generate the following object, which allows you to easily access the value for a given key:
{
"AccountEmail": "anshuman.ceg+Dev#gmail.com",
"AccountName": "DevABC",
"ManagedOrganizationalUnit": "Security (ou-nzx5-8ajd1561)",
"SSOUserEmail": "anshuman.ceg+Dev#gmail.com",
"SSOUserFirstName": "John",
"SSOUserLastName": "Smith"
}
If the object keys in the input happen not to be "Key" and "Value" and you can't use from_entries, select would be a good approach:
jq --arg k 'AccountName' -r '.[] | select(.Key == $k).Value'

JQ, two queries, over different part of json, Merge it back

I am trying to extract kubeconfig data with jq.
kubectl config view --raw -o json | jq ...
There is a json produced of this kind:
{
"kind": "Config",
"apiVersion": "v1",
"preferences": {},
"clusters": [
{
"name": "some-name",
"cluster": {
"server": "https://some-url",
"certificate-authority-data": "some-cert"
}
},
{
"name": "another-name",
"cluster": {
"server": "https://another-url",
"certificate-authority-data": "another-cert"
}
}
],
"users": [
{
"name": "some-name",
"user": {
"username": "some-user",
"password": "some-password"
}
},
{
"name": "another-name",
"user": {
"username": "another-user",
"password": "another-password"
}
}
],
"contexts": [],
"current-context": "some-context"
}
Question #1:
For a given name ,"some-name", I'd like to extract json:
{
url: "https://some-url",
cert: "some-cert",
username: "some-user",
password: "some-password"
}
Question #2:
"users" sub-section can have other format
"users": [
{
"name": "...",
"user": {
"exec": {
...
}
Where .user.username or .user.password or both can be missing
In this case overall query should return "{}", even though, "clusters" query/branch has result
Question 3, as a follow up to Jeff Mercado answer:
I want to get all clusters, joined (grouped by) name:
Looking at the manual, https://stedolan.github.io/jq/manual/#Builtinoperatorsandfunctions ,
section "Multiplication, division, modulo: *, /, and %", example:
jq '{"k": {"a": 1, "b": 2}} * {"k": {"a": 0,"c": 3}}' => {"k": {"a": 0, "b": 2, "c": 3}}'
gives presumably right result, assuming "k" is value of "name". So, grouping by "k", merging (*) the results.
I produced following query:
echo "${json}" | jq -r '(.clusters[] | {(.name): {url: .cluster.server, cert: .cluster["certificate-authority-data"]}}) * (.users[] | {(.name): {user: .user.username, password: .user.password}})'
First part returns {"name": {url: cert}}, second part is {"name": {username, password}}
However, result is not merge as in jq Manual, but something else ... product ?
{
"some-name": {
"url": "https://some-url",
"cert": "some-cert",
"user": "some-user",
"password": "some-password"
}
}
{
"another-name": {
"url": "https://another-url",
"cert": "another-cert"
},
"some-name": {
"user": "some-user",
"password": "some-password"
}
}
{
"some-name": {
"url": "https://some-url",
"cert": "some-cert"
},
"another-name": {
"user": "another-user",
"password": "another-password"
}
}
{
"another-name": {
"url": "https://another-url",
"cert": "another-cert",
"user": "another-user",
"password": "another-password"
}
}
Why/what is it ? Kind of following idea of the product ('*') but not of the jq tutorial as I (most likely, incorrectly) understand it
Experimentation:
I have 2 queries now producing partial result.
Let's grab original json (above) in and parse:
read -d '' json << EOF
...
EOF
queries:
echo "${json}" | jq -r '.clusters[] | select(.name=="some-name") | .cluster | {url: .server, cert: .["certificate-authority-data"]}' &&\
echo "${json}" | jq -r '.users[] | select(.name=="some-name") | .user | {user: .username, password: .password}'
Will produce the split output:
{
"url": "https://some-url",
"cert": "some-cert"
}
{
"user": "some-user",
"password": "some-password"
}
Or, with key added for further merge:
echo "${json}" | jq -r '.clusters[] | select(.name=="some-name") | {name: .name, url: .cluster.server, cert: .cluster["certificate-authority-data"]}' &&\
echo "${json}" | jq -r '.users[] | select(.name=="some-name") | {name: .name, user: .user.username, password: .user.password}'
Will produce:
{
"name": "some-name",
"url": "https://some-url",
"cert": "some-cert"
}
{
"name": "some-name",
"user": "some-user",
"password": "some-password"
}
"name" is not needed but can be used as a join operation
So you already know how to get the cluster and user by name separately, first step is to select them both within a single filter:
(.clusters[] | select(.name == $name).cluster), (.users[] | select(.name == $name).user)
This will yield two separate objects, the cluster, then the user. But we want to merge them. There's plenty of ways to do this. You could add them (+) directly or merge them (*) but no real difference there. You'll just want to remap the properties to the names you wanted where needed.
(.clusters[] | select(.name == $name).cluster | {url: .server, cert: ."certificate-authority-data"})
+
(.users[] | select(.name == $name).user | {username, password})
Pass the name in as a parameter to your filter;
$ kubectl config view --raw -o json | jq --arg name some-name '
(.clusters[] | select(.name == $name).cluster | {url: .server, cert: ."certificate-authority-data"})
+
(.users[] | select(.name == $name).user | {username, password})
'
For the second part of your question, if it turns out the mapped user is missing key properties and you want to omit them, just add another select filter to the end to test for those properties and replace with an empty object if nothing is found:
... | select(has("username") and has("password")) // {}
jqplay

JQ only returns one CIDR block from AWS CLI

I am trying to read the CIDR blocks from the VPCs in AWS on the AWS CLI. I will use this in a script when I'm done. I am using jq to parse the info:
aws ec2 describe-vpcs --region=us-east-1 | jq -r '.Vpcs[].CidrBlock'
10.200.3.0/24
However, jq only returns one of the two CIDR blocks in the VPC. This is the original json:
{
"Vpcs": [
{
"CidrBlock": "10.200.3.0/24",
"DhcpOptionsId": "dopt-d0aa95ab",
"State": "available",
"VpcId": "vpc-00de11103235ec567",
"OwnerId": "046480487130",
"InstanceTenancy": "default",
"Ipv6CidrBlockAssociationSet": [
{
"AssociationId": "vpc-cidr-assoc-09f19d81c2e4566b9",
"Ipv6CidrBlock": "2600:1f18:1f7:300::/56",
"Ipv6CidrBlockState": {
"State": "associated"
},
"NetworkBorderGroup": "us-east-1"
}
],
"CidrBlockAssociationSet": [
{
"AssociationId": "vpc-cidr-assoc-0511a5d459f937899",
"CidrBlock": "10.238.3.0/24",
"CidrBlockState": {
"State": "associated"
}
},
{
"AssociationId": "vpc-cidr-assoc-05ad73e8c515a470f",
"CidrBlock": "100.140.0.0/27",
"CidrBlockState": {
"State": "associated"
}
}
],
"IsDefault": false,
"Tags": [
{
"Key": "environment",
"Value": "int01"
},
{
"Key": "Name",
"Value": "company-int01-vpc"
},
{
"Key": "project",
"Value": "company"
}
]
}
]
}
Why does jq only return part of the info I'm after? I need to get all VPC CIDR blocks in the output.
You have two keys CidrBlock and CidrBlockAssociationSet under the Vpcs array.
aws ec2 describe-vpcs --region=us-east-1 |
jq -r '.Vpcs[] | .CidrBlock, .CidrBlockAssociationSet[].CidrBlock'
10.200.3.0/24
10.238.3.0/24
100.140.0.0/27
and this is an invariant solution:
aws ... | jq -r '.. | if type == "object" and has("CidrBlock") then .CidrBlock else empty end'
and, inspired by jq170727's answer, a less expressive form:
aws ... | jq -r '.. | objects | .CidrBlock // empty'
Here is a filter inspired by Dmitry's answer which is slightly shorter: .. | .CidrBlock? | values
Try it online!

JQ filter and output format

For an input below:
[{
"commit": {
"author": {
"name": "Stephen Dolan",
"email": "mu#netsoc.tcd.ie",
"date": "2013-06-22T16:30:59Z"
},
"committer": {
"name": "Stephen Dolan",
"email": "mu#netsoc.tcd.ie",
"date": "2013-06-22T16:30:59Z"
},
"message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161"
"url":"https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f"
},
{
...
}
}]
How can JQ generate a delimited string from different objects as shown below?
"Stephen Dolan", "https://api.github.com/repos/stedolan/jq/commits/d25341478381063d1c76e81b3a52e0592a7c997f", "2013-06-22T16:30:59Z"
Collect the fields you want in an array and use #csv to convert to a CSV row. Make sure you get the raw output.
jq -r '.[] | [ .commit.author.name, .commit.url, .commit.author.date ] | #csv' input.json

Resources