Double condition in array with JQ - jq

My JSON is an array of one object like this:
[{
"id": 125650,
"status": "success",
"name": "build_job",
"artifacts": [
{
"file_type": "archive",
"size": 72720116,
"filename": "artifacts.zip",
"file_format": "zip"
},
{
"file_type": "metadata",
"size": 1406,
"filename": "metadata.gz",
"file_format": "gzip"
}
]
}]
I want to select only the object ID if the following conditions matches:
status == success
name == build_job
artifacts.size > 0 where file_type == archive
I'm stuck on the last condition, I can select artifacts with size > 0, OR artifacts where file_type = archive, but not both at the same time.
Here's my current query :
| jq '.[0] | select(.name == "build_job" and .status == "success" and .artifacts[].file_type == "archive") | .id'
Can you help me with that ?

For the last condition, you presumably mean something like:
all(.artifacts[];
if .file_type == "archive" then .size > 0 else true end)
which can also be written as:
all(.artifacts[] | select(.file_type == "archive");
.size > 0)
Iā€™d recommend using either all or any, depending on your requirements.

Try this:
.[0] | select(
.name == "build_job" and .status == "success" and (
.artifacts[] | select(.file_type == "archive") | length > 0
)
) | .id
This selects successful build_jobs containing one or more archive artifacts. Unfortunately, multiple ids are returned if there's more than one such artifacts. Here's how to wrap the expression to fix that:
[
.[] | select(
.name == "build_job" and .status == "success" and (
.artifacts[] | select(.file_type == "archive") | length > 0
)
)
] | unique | .[].id

For the last condition, take the array .artifacts, reduce it to those elements matching your criteria map(select(.file_type == "archive")) and test the resulting array's length length > 0.
All together:
.[0] | select(
.name == "build_job" and
.status == "success" and (
(.artifacts | map(select(.file_type == "archive"))) | length > 0
)
)
| .id

Related

Conditionally output a field?

In this example I only want isGreaterThanOne field to be shown if it's true. Here's what I started with (always shown)
echo '[{"a":5},{"a":1}]' | jq '[.[] | {value:.a, isGreaterThanOne:(.a>1)}]'
I inserted an if statement
echo '[{"a":5},{"a":1}]' | jq '[.[] | {value:.a, X:(if .a>1 then "Y" else "N" end) }]'
Then got stuck trying to move the field into the conditional. Also it seems like I must have an else with an if
echo '[{"a":5},{"a":1}]' | jq '[.[] | {value:.a, (if .a>1 then (K:"Y)" else (L:"N") end) }]'
I want the below as the result (doesn't need to be pretty printed)
[
{
"value": 5,
"X": "Y"
},
{
"value": 1,
}
]
Using if, make one branch provide an empty object {} which wouldn't contain the extra field:
map({value: .a} + if .a > 1 then {X: "Y"} else {} end)
Demo
Alternatively, equip only selected items with the extra field:
map({value: .a} | select(.value > 1).X = "Y")
Demo
Output:
[
{
"value": 5,
"X": "Y"
},
{
"value": 1
}
]

jq Split value on base space and join to one string

I would like to ask for help. I need to split values from key "Text" on base space " " and join to one line. In actually code I calculate with exactly position but if key Text has S10 is show only S1.
My input
[
{
"PartNumber": "5SE32DFVLG002",
"ClassificationNo": "500001",
"StringValue": "R0050SWSW",
"Field": "95001",
"Text": "S1 W1 cr.sec+colour"
},
{
"PartNumber": "5SE32DFVLG002",
"ClassificationNo": "500001",
"StringValue": "R0050SWSW",
"Field": "95004",
"Text": "S1 W10 cr.sec+colour"
}
]
My actually condition in jq play
[.Oslm[] | select(.ClassificationNo=="500001" and .StringValue!="") |
{PartNumber,ClassificationNo,StringValue,Field,Text}] |
sort_by(.Field) | .[] | [.PartNumber,.ClassificationNo,
.Field[3:5],.Text[0:2] + "-" + .Text[3:5] + .StringValue[0:1], "Test
", .StringValue[1:10]] | join(";")
Actual result
5SE32DFVLG002;500001;95001;S1-W1R;TEST;0050SWSW
5SE32DFVLG002;500001;95004;S1-W1R;TEST;0050SWSW
I would like to have this result
5SE32DFVLG002;500001;95001;S1-W1R;TEST;0050SWSW
5SE32DFVLG002;500001;95004;S1-W10R;TEST;0050SWSW
Modify the part involving generation of .Text to something simpler using split() method in jq that can be used to split on a single white-space. This way, you are not reliant on the length of the sub-fields you want to extract
( .Text | split(" ") | .[0] + "-" + .[1] ) + .StringValue[0:1]
i.e. with full code
.[] | [ select( .ClassificationNo =="500001" and .StringValue != "" ) |
{
PartNumber,
ClassificationNo,
StringValue,
Field,
Text
} ] |
sort_by(.Field) |
map(
.PartNumber,
.ClassificationNo,
.Field[3:5],
( .Text | split(" ") | .[0] + "-" + .[1] ) + .StringValue[0:1],
"Test", .StringValue[1:10]
) |
join(";")
demo at jqplay

Extract nested properties from an array of objects

I have the following JSON file :
{
"filter": [
{
"id": "id_1",
"criteria": {
"from": "mail#domain1.com",
"subject": "subject_1"
},
"action": {
"addLabelIds": [
"Label_id_1"
],
"removeLabelIds": [
"INBOX",
"SPAM"
]
}
},
{
"id": "id_2",
"criteria": {
"from": "mail#domain2.com",
"subject": "subject_1"
},
"action": {
"addLabelIds": [
"Label_id_2"
],
"removeLabelIds": [
"INBOX",
"SPAM"
]
}
}
]
}
And I would like to extract emails values : mail#domain1.com and mail#domain2.com
I have tried this command:
jq --raw-output '.filter[] | select(.criteria.from | test("mail"; "i")) | .id'
But does not work, I get this error :
jq: error (at <stdin>:1206): null (null) cannot be matched, as it is
not a string exit status 5
Another point : how to display the value of "id" key, where "from" key value = mail#domain1.com ?
So in my file id = id_1
Do you have an idea ?
If you only need to extract the emails from .criteria.from then this filter is enough as far as I can tell:
jq --raw-output '.filter[].criteria.from' file.json
If some objects don't have a criteria object then you can filter out nulls with:
jq --raw-output '.filter[].criteria.from | select(. != null)' file.json
If you want to keep the emails equal to "mail#domain1.com":
jq --raw-output '.filter[].criteria.from | select(. == "mail#domain1.com")' file.json
If you want to keep the emails that start with "mail#":
jq --raw-output '.filter[].criteria.from | select(. != null) | select(startswith("mail#"))' file.json
I would like to extract emails values
There is a wide spectrum of possible answers, with these
amongst the least specific with respect to where in the JSON the email addresses occur:
.. | objects | .from | select(type=="string")
.. | strings | select(test("#([a-z0-9]+[.])+[a-z]+$"))

regex replacement for whole object tree / reverse operation to `tostring`

So I have big json, where I need to take some subtree and copy it to other place, but with some properties updated (a lot of them). So for example:
{
"items": [
{ "id": 1, "other": "abc"},
{ "id": 2, "other": "def"},
{ "id": 3, "other": "ghi"}
]
}
and say, that i'd like to duplicate record having id == 2, and replace char e in other field with char x using regex. That could go (I'm sure there is a better way, but I'm beginner) something like:
jq '.items |= . + [.[]|select (.id == 2) as $orig | .id=4 | .other=($orig.other | sub("e";"x"))]'<sample.json
producing
{
"items": [
{
"id": 1,
"other": "abc"
},
{
"id": 2,
"other": "def"
},
{
"id": 3,
"other": "ghi"
},
{
"id": 4,
"other": "dxf"
}
]
}
Now that's great. But suppose, that there ins't just one other field. There are multitude of them, and over deep tree. Well I can issue multiple sub operations, but assuming, that replacement pattern is sufficiently selective, maybe we can turn the whole JSON subtree to string (trivial, tostring method) and replace all occurences using singe sub call. But how to turn that substituted string back to ā€” is it call object? ā€” to be able to add it back to items array?
Here's a program that might be a solution to the general problem you are describing, but if not at least illustrates how problems of this type can be solved. Note in particular that there is no explicit reference to a field named "other", and that (thanks to walk) the update function is applied to all candidate JSON objects in the input.
def update($n):
if .items | length > 0
then ((.items[0]|keys_unsorted) - ["id"]) as $keys
| if ($keys | length) == 1
then $keys[0] as $key
| (.items|map(.id) | max + 1) as $newid
| .items |= . + [.[] | select(.id == $n) as $orig | .id=$newid | .[$key]=($orig[$key] | sub("e";"x"))]
else .
end
else .
end;
walk(if type == "object" and has("items") then update(2) else . end)

jq not getting expected output

My JSON looks like this.
"[{
changes": [
{
"change": "{users=[7], submitted=true}",
"date": "2016-11-13T14:34:27.353Z",
"user": "abcd"
}
]
}]
Expected Output:
{
id: null,
date: "2016-11-13T14:34:27.353Z",
type: "submission",
user: abcd,
_processDate: todaysDate
}
JQ I tried
[.[][] as $source |
$source.changes[] as $log |
$log.change |
{
submitted: .| (scan("submitted=(?<submitted>[^,}]+)") // [""] ) | .[0],
rejected: .| (scan("rejected=(?<rejected>[^,}]+)") // [""] ) | .[0]
} as $change |
[
(
select($change.submitted == "true") |
{
id: $source.id,
date: $log.date,
type: "submission",
user: $log.user,
_processDate: now | todate
}),
(select($change.rejected == "true") |
{
id: $source.id,
date: $log.date,
type: "rejection",
user: $log.user,
_processDate: now | todate
}
)
] |
.[]]
There could 'rejections' in the json and the output should display the rejections .
My JQ is not yielding expected output.
Any pointers on how to fix this query.
Thank you for your help.
Appreciate it.
I'd take a completely different approach and do this instead.
(now | todate) as $_processDate | [
.[].changes[]
| (.change
| scan("\\b(submitted|rejected)=true\\b")[]
| {submitted:"submission",rejected:"rejection"}[.]) as $type
| {id, date, $type, user, $_processDate}
]
First take note of the current date at the beginning. Then determine what type of change it is. Assuming that "submitted" and "rejected" (or other "types") are mutually exclusive, easier to match on the key name. Then build up the result. This will keep the results in an array.
https://jqplay.org/s/S65ySzbF30

Resources