如何使用其他方式重写jq中的输出

时间:2019-08-19 22:01:53

标签: linux jq

我正在尝试更改它,以便当CrashTested为false时,它输出,而当true时,它输出

这是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"
}
   ]
}

我尝试了以下操作:

$ 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"

我正在尝试获得以下输出:

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

我使用的是jq版本 jq-1.5-1

我应该使用map()还是以其他方式进行操作?

2 个答案:

答案 0 :(得分:1)

如果删除map,则将获得指定值的流。不过,按照以下几行写一些东西可能更有意义:

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

或:

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

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

答案 1 :(得分:0)

即使该问题专门针对 jq ,该问题的类型在JSON操作中也很常见,并且或者也可以使用walk-path实现Unix实用程序 jtc

bash $ <cars.json jtc -x'<r>z[Cars][:]' -y[Name] -y[ID] -y'<r:"no">f[CrashTested]<"true">j<r:"yes">v' -T{{r}} 
"Toyota Prius"
1
"no"
"Honda Accord"
2
"yes"
"VW Beetle"
3
"no"
...

输出示例jtc的几个功能:

  • 对帐walk-paths(当每个-y前面有一个公共-x时)
  • 使用名称空间变量r应用于模板插值(-T{{r}}
  • 最后(-y)个使用默认值(r:"no")的步行路径示例,如果进一步的步行失败(如果步行没有失败,则r)最终被设置为值"yes"

PS>披露:我是jtc-用于JSON操作的shell cli工具的创建者