user11904513
user11904513

Reputation:

how to use if else to rewrite output in jq

I am trying to change it so that when CrashTested is false, then it outputs no and when true, then yes

Here is the json:

{
    "Cars": [
        {   "Name": "Toyota Prius",
            "ID": 1,
            "CrashTested": "false"
},

        {   "Name": "Honda Accord",
            "ID": 2,
            "CrashTested": "true"
},
        {   "Name": "VW Beetle",
            "ID": 3,
            "CrashTested": "false"
},

        {   "Name": "Acura TL",
            "ID": 4,
            "CrashTested": "true"
},

        {   "Name": "Dodge Charger",
            "ID": 5,
            "CrashTested": "false"
},
        {   "Name": "Ford Focus",
            "ID": 6,
            "CrashTested": "true"
}
   ]
}

I have tried the following:

$ jq -r '.Cars[] | .Name, .ID, map(if .CrashTested == "true" then "yes" elif .CrashTested == "false" then "no" else "unknown" end)' < cars.json
Toyota Prius
1
jq: error (at <stdin>:31): Cannot index string with string "CrashTested"

I'm trying to get the following output:

"Toyota Prius"
1
"no"
"Honda Accord"
2
"yes"
...

I'm on jq version jq-1.5-1

Should I be using map() or going about this a different way?

Upvotes: 4

Views: 1407

Answers (1)

peak
peak

Reputation: 116640

If you remove map then you will get a stream of the specified values. It might make more sense, though, to write something along the following lines:

.Cars[]
| [.Name, .ID, (if .CrashTested == "true" then "yes" elif .CrashTested == "false" then "no" else "unknown" end)]
| @csv 

or:

def yn:
  if . == true or . == "true" then "yes"
  elif . == false or . == "false" then "no"
  else "unknown"
  end;

.Cars[]
| [.Name, .ID, (.CrashTested | yn) ]

Upvotes: 4

Related Questions