Issue
I have a JSON object that looks like this:
[{"name":"NAME_1"},"NAME_2"]
["NAME_1", "NAME_2"]
Some of the entries in the array are an object with a key "name" and some are just a string of the name. I am trying to extract an array of the names. Using
jq -cr '.[].name // []'
throws an error as it is trying to index .name of the string object. Is there a way to check if it is a string, and if so just use its value instead of .name?
Solution
echo '[{"name":"NAME_1"},"NAME_2"]' \
| jq '[ .[] | if (.|type) == "object" then .name else . end ]'
[
"NAME_1"
"NAME_2"
]
Ref:
- https://stedolan.github.io/jq/manual/#ConditionalsandComparisons
- https://stedolan.github.io/jq/manual/#type
As @LéaGris comments, a simpler version
jq '[ .[] | .name? // . ]' file
- https://stedolan.github.io/jq/manual/#ErrorSuppression/OptionalOperator:%3f
- https://stedolan.github.io/jq/manual/#Alternativeoperator://
Answered By - glenn jackman Answer Checked By - Willingham (WPSolving Volunteer)