In my sample json below, I can filter records where charge is null with jq -M ' map(select(.charge == null)) '
[
{
"id": 1,
"name": "vehicleA",
"state": "available",
"charge": 100
},
{
"id": 2,
"name": "vehicleB",
"state": "available",
},
{
"id": 3,
"name": "vehicleB",
"state": "available",
"charge": 50
}
]
which returns:
{
"id": 2,
"name": "vehicleB",
"state": "available",
}
How would one only get id
and the value associated with id
of the filtered records so that adding this step to the above query would return 2
?
Objective: Parse the json from a file or end-point using `jq` and retrieve id-value pair for further process. Additional condition: if the field `name` have pattern: “test1, test2, test3… testN” then create a CSV file with fields: id,name,value.
In order to get a key-value pair from a KiiObject, call the get() method of the KiiObject class. Specify the key for the value to get as the argument of the get() method. The value of the key at the first level of the JSON document hierarchy will be obtained.
JSON is basically a collection of name/value pairs, where the name will always be a string and values can be a string (in double quotes), a number, a boolean (true or false), null, an object, or an array. Each name-value pair will be separated by a comma.
jq usually outputs non-ASCII Unicode codepoints as UTF-8, even if the input specified them as escape sequences (like "\u03bc"). Using this option, you can force jq to produce pure ASCII output with every non-ASCII character replaced with the equivalent escape sequence.
If you would like an array of ids for items without a charge you could use this filter:
.items | map(select(.charge == null) | .id)
Try it online at jqplay.org
If you want the values enumerated instead of being collected into an array this is better:
.items[] | select(.charge == null) | .id
Try it online at jqplay.org
Your question is not exactly accurate:
map(select(.charge == null))
is not an object as in the example, but an array of a single objectIn any case, you can extract the .id
from the result of map
like this:
jq -M 'map(select(.charge == null)) | .[].id' file.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With