简体   繁体   English

如何使用jq将我的JSON转换为CSV?

[英]How can I convert my JSON to CSV using jq?

I have the following JSON data: 我有以下JSON数据:

{"id":"111","case":"Y","custom":{"speech invoked":"no","input method":"hard","session ID":"420"}}

How can I convert it to CSV format using jq so my result looks like this? 如何使用jq将其转换为CSV格式,所以我的结果如下所示?

id,case,session Id,speech invoked,input method

111,Y,420,no,hard

I tried the following, but it didn't work: 我尝试了以下,但它不起作用:

{(.id),(.case),(.custom."session Id"),(.custom."speech invoked"),(.custom."input method")}

If not possible any perl or shell solution is appreciated. 如果不可能,任何perl或shell解决方案都是值得赞赏的。

在Joe Harris的回答的基础上,您可以使用@csv过滤器,以便在必要时正确引用和转义字符串:

jq -r '[.case, .custom."speech invoked", .custom."input method"] | @csv'

Using perl wasn't a good solution for me but after a bit of trial and error I figured out you can do it with just jq using the join() operator. 使用perl对我来说不是一个好的解决方案,但经过一些试验和错误后,我发现你可以使用join()运算符只使用jq

First make an array of the output you need, then join the array elements using commas. 首先创建所需输出的数组,然后使用逗号连接数组元素。

jq -r '[.case, .custom."speech invoked", .custom."input method"] | join(", ")'

Enjoy. 请享用。 :) :)

Using jq, you can use this filter: 使用jq,您可以使用此过滤器:

with_entries(select(.key != "custom")) + .custom
    | to_entries
    | map(.key), map(.value)
    | @csv

Just note that written this way, the "custom" properties will always be written in the end, no matter what order the properties are in. 请注意,以这种方式编写,无论属性的顺序如何,“自定义”属性最终都会写入。

Here is another solution. 这是另一种解决方案。 If data.json contains the sample data then 如果data.json包含样本数据

jq -M -s -r 'map(.+.custom|del(.custom)) | (.[0]|keys_unsorted), (.[]|[.[]]) | join(",")' data.json

will produce 会产生

id,case,speech invoked,input method,session ID
111,Y,no,hard,420

Using Perl and its JSON module: 使用Perl及其JSON模块:

#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

use JSON;

my $input = << '__JSON__';
{"id":"111","case":"Y","custom":{"speech invoked":"no","input method":"hard","session ID":"420"}}
__JSON__

my $struct = decode_json($input);

my @header = grep ! ref $struct->{$_}, keys %$struct;
push @header, map keys %{ $struct->{$_} },
              grep ref $struct->{$_},
              keys %$struct;

my @row = grep ! ref, values %$struct;
push @row, map values %$_, grep ref, values %$struct;

say join ',', @header;
say join ',', @row;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM