Shell script to extract data from a list of files and saving it as a csv
To parse JSON-encoded data robustly, you will need a JSON codec. This pretty much means Perl or Python (or Ruby ...). Since I'm a Perl guy, here's a Perl solution.
First off a one-liner:
$ perl -MJSON -ne 'BEGIN { print("clientId;intent;time;userId\n"); } eval { my $obj = from_json($_); my $msg = $obj->{msg}; $msg =~ s/^.*{\s*|\s*,\s*}.*$//g; my %m = map { m/^([^:]*):\s*(.*)/; ($1, $2) } split(/,\s+/, $msg); print("$m{clientId};$m{intent};$obj->{time};$m{userId}\n"); }; warn($@) if ($@);' <x
clientId;intent;time;userId
5003700557;YesIntent;2019-01-21T12:23:10.323Z;AFC5EH5PIHHLO4XS7SG
Since that is a little excessive, even for Perl, here's a readable script as well:
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
print("clientId;intent;time;userId\n");
while (<>) {
# Don't choke on malformed lines
eval {
my $obj = from_json($_);
my $msg = $obj->{msg};
$msg =~
s/^.*{\s* # Trim up to and including the leading '{'
|
\s*,\s*}.*$ # Trim trailing ',}'
//gx;
# Split $msg into key-value pairs
my %m = map {
m/^([^:]*) # Stuff that isn't ':'
:\s* # Field separator
(.*) # Everything after the separator
/x;
($1, $2)
} split(/,\s+/, $msg);
print("$m{clientId};$m{intent};$obj->{time};$m{userId}\n");
};
warn($@) if ($@);
}