【问题标题】:JQ -c / --compact-output not working properly? Json ParsingJQ -c / --compact-output 不能正常工作? json解析
【发布时间】:2018-02-15 23:36:27
【问题描述】:

我刚刚在一个小时前发布的一个问题中被介绍给 JQ,我正在解析一个非常大的数据库,但是使用 JQ,输出看起来像这样:

"removedforprivacy@gmail.com"  
"john"  
"smith"  
null  
null  
"123 road st"  
null  
"Columbia"  
"29203"  
"SC"  
null  

我希望它看起来像这样:

"removedforprivacy@gmail.com"
"john"
"smith"
null
null
"123 road st"
null
"Columbia"
"29203"
"SC"
null

甚至更好:

"removedforprivacy@gmail.com","john","smith",null,null,"123,road,st",null,"Columbia","29203","SC",null

我目前正在使用这个命令:

jq -c '(.email, .first_name, .last_name, .ip, .address, .address1, .address2, .city, .zip, .state, .phone)' file.json > file2.json 

我也试过使用这个命令:

jq -compact-output '(.email, .first_name, .last_name, .ip, .address, .address1, .address2, .city, .zip, .state, .phone)' file.json > file2.json 

但 file2.json 仍然显示如下数据:

"removedforprivacy@gmail.com"  
"john"  
"smith"  
null  
null  
"123 road st"  
null  
"Columbia"  
"29203"  
"SC"  
null  

简而言之,我想将输出转换为看起来像 csv 或 csv 的东西,以便更好地管理它。

该命令不起作用,只需要该命令一次使用。

【问题讨论】:

    标签: json database parsing jq


    【解决方案1】:

    如果您想要 CSV,那么您当然可以简单地使用 @csv 过滤器,但 @csv 会将 null 转换为空字段:

    "removedforprivacy@gmail.com","john","smith",,,"123 road st",,"Columbia","29203","SC",
    

    要以您想要的方式处理字符串和null,您可以将@tsv 与-r 命令行选项结合使用,如下所示:

    map(if type == "string" then "\"\(.)\"" else "null" end)
    | @tsv | gsub("\t";",") 
    

    根据您的输入,这会产生:

    "removedforprivacy@gmail.com","john","smith",null,null,"123 road st",null,"Columbia","29203","SC",null
    

    对于其他变体,您可能希望使用 join/1 和/或 -j 命令行选项。

    -c 命令行选项

    如手册所述:

    使用此选项将导致更紧凑的输出,而不是将每个 JSON 对象放在一行中。

    这里的“JSON 对象”是指“JSON 实体”。

    【讨论】:

    • 您可以帮我写出命令吗?我问了另一个问题,我遇到了问题,我使用了这个命令jq -r 'to_entries[] | [.email, .first_name, .last_name, .ip, .address, .address1, .address2, .city, .zip, .state, .phone] | @csv' file.json > file3.json,但它给出的空行看起来像这样:` ,,,,,,,,,, ,,,,,,,,,, , ,,,,,,,,, ,,,,,,,,,, ,,,,,,,,,, `
    • 你为什么使用to_entries?根据原始问题,您似乎应该从 jq -r '[.email, .first_name, ...] | @csv' 之类的内容开始
    • 天哪!!!!非常感谢,我已经在这几个小时了,我不知道为什么它之前没有工作我使用了类似的命令,非常感谢@peak !!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-20
    • 2010-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多