如何使用jq将我的JSON转换为CSV? [英] How can I convert my JSON to CSV using jq?
本文介绍了如何使用jq将我的JSON转换为CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下JSON数据:
I have the following JSON data:
{"id":"111","case":"Y","custom":{"speech invoked":"no","input method":"hard","session ID":"420"}}
如何使用 jq 将其转换为CSV格式,以便我的结果像这样?
How can I convert it to CSV format using jq so my result looks like this?
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")}
如果不可能,任何perl或shell解决方案
If not possible any perl or shell solution is appreciated.
推荐答案
使用Perl及其JSON模块:
Using Perl and its JSON module:
#!/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;
这篇关于如何使用jq将我的JSON转换为CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文