我有一个带有字段的json对象,该字段可以包含字符串或数组值。
{
"roles": ["ADMIN", "USER"]
"user_id": 100,
"message": "abc added a user xyz",
"level": "info",
"created_at": "2014-10-12 14:06:37"
}
{
"roles": "ADMIN"
"user_id": 102,
"message": "a added a user b",
"level": "info",
"created_at": "2014-10-12 14:06:37"
}
我想将角色字段转换为csv,并按原样保留其余字段。
{
"roles": "ADMIN,USER"
"user_id": 100,
"message": "abc added a user xyz",
"level": "info",
"created_at": "2014-10-12 14:06:37"
}
{
"roles": "ADMIN"
"user_id": 102,
"message": "a added a user b",
"level": "info",
"created_at": "2014-10-12 14:06:37"
}
我尝试阅读文档,但找不到只转换单个字段的构造。这可以用Jq实现吗?
答案 0 :(得分:2)
一种选择是使用过滤器:
.roles |= if type == "array" then join(",") else . end
在第一个示例中,这将产生值:" ADMIN,USER"
更强大的过滤器将是:
.roles |= if type == "array" then map(tostring)|join(",") else . end
更强大的是在@csv
子句中使用then
,但这会产生比您想要的更多的引号:
"\"ADMIN\",\"USER\""
所以你可能想考虑使用@tsv;它会产生:
"ADMIN\tUSER"