Reputation: 89
I have a JSON file as below.
{
"card":{
"cardName":"10AN10G",
"portSignalRates":[
"10AN10G-1-OTU2",
"10AN10G-1-OTU2E",
"10AN10G-1-TENGIGE",
"10AN10G-1-STM64"
],
"listOfPort":{
"10AN10G-1-OTU2":{
"portAid":"10AN10G-1-OTU2",
"signalType":"OTU2",
"tabNames":[
"PortDetails"
],
"requestType":{
"PortDetails":"PTP"
},
"paramDetailsMap":{
"PortDetails":[
{
"type":"dijit.form.TextBox",
"name":"signalType",
"title":"Signal Rate",
"id":"",
"options":[
],
"label":"",
"value":"OTU2",
"checked":"",
"enabled":"false",
"selected":""
},
{
"type":"dijit.form.TextBox",
"name":"userLabel",
"title":"Description",
"id":"",
"options":[
],
"label":"",
"value":"",
"checked":"",
"enabled":"true",
"selected":""
},
{
"type":"dijit.form.Select",
"name":"Frequency",
"title":"Transmit Frequency"
}
]
}
}
}
}
}
I require the output to be:
signalType:"Signal Rate",
userLabel:"Description",
Frequency:"Transmit Frequency",.. ,.....
I tried with:
grep -oP '(?<=\"title\":\")[^"]*' file > outfile
but this just splits the value of title and returns.
Can I use perl to access elements of the JSON data that I want?
Upvotes: 3
Views: 2772
Reputation: 6388
Yes you can use the JSON
perl module. Of course it meeds to be installed via cpan
, cpanm
or your system's packaging system. Parse the JSON into a hash and then use that in the normal way from Perl. Here's a quick example:
use JSON;
use IO::All;
use strict;
use warnings;
my $data < io '/tmp/data.json';
my $j = decode_json($data);
use DDP; # for quick debug printing
p $j->{card}{listOfPort}{"10AN10G-1-OTU2"}{paramDetailsMap}{PortDetails}[0]{title}
"Signal Rate"
You might want to use some deep diving techniques to get at the inner values more easily/programmatically (take a look at the Data::Diver
module for that) - my example is meant to show only that it is possible and a bit of the mechanics of mapping JSON into a perl
hash with the excellent JSON module. The documentation has lots of useful examples.
Upvotes: 2
Reputation: 12089
Perl on the command line:
perl -pe 's/"name":"([^"]+)","title":/"$1":/g' file > outfile
Output (pertinent part):
{"card": ... "signalType":"Signal Rate", ... "userLabel":"Description", ... "Frequency":"Transmit Frequency" ... }
Upvotes: 0
Reputation: 42093
I suggest to use decode_json
instead of a regex. First, install the JSON module from CPAN:
sudo perl -MCPAN -e 'install JSON'
Alternatively you can use apt-get
on Ubuntu:
sudo apt-get install libjson-pp-perl
Once it is installed, you can use this code:
my $json = '{... your json string ...}';
my $decoded = decode_json($json);
$decoded->{'card'}{'listOfPort'}{'10AN10G-1-OTU2'}{'signalType'}
You can find more details in this article.
Upvotes: 4