Reputation: 33
I have a json file that requires parsing. Using scripting like sed/awk or perl, how to extract value30 and substitute that to value6 prefixed by string "XX" (eg. XX + value30). Where:
[ {"field6" : "value6", "field30" : "value30" }, { "field6" : "value6", "field30" : "value30" } ]
Upvotes: 1
Views: 717
Reputation: 27538
If I understand you correctly, this program should do what you're after:
use JSON qw(decode_json encode_json);
use strict;
use warnings;
# set the input line separator to undefined so the next read (<>) reads the entire file
undef $/;
# read the entire input (stdin or a file passed on the command line) and parse it as JSON
my $data = decode_json(<>);
my $from_field = "field6";
my $to_field = "field30";
for (@$data) {
$_->{$to_field} = $_->{$from_field};
}
print encode_json($data), "\n";
It relies on the JSON module being installed, which you can install via cpanm (which should be available in most modern Perl distributions):
cpanm install JSON
If the program is in the file substitute.pl
and your json array is in data.json
, then you would run it as:
perl substitute.pl data.json
# or
cat data.json | perl substitute.pl
It should produce:
[{"field30":"value6","field6":"value6"},{"field30":"value6","field6":"value6"}]
Replacing field30
's value iwth field6
's.
Is this what you were attempting to do?
Upvotes: 3