manipulating a JSON to correct format in perl - json

I have a JSON that prints
{"d":{"success":true,"drivers":[{"FIRST_NAME":"JOHN","LAST_NAME":"SMITH"},{"FIRST_NAME":"JANE","LAST_NAME":"DOE"}]}}
The names change depending on what was found in the database. I need to push this in this format for each result resturned in the JSON:
push(#$dummy_data, {'name' => 'testname', 'key' => 'somekey-1234'});
push(#$dummy_data, {'name' => 'testname2', 'key' => 'somekey-5678'});
So for this example it would be John Smith in place of testname and Jane for testname2
How would I do this so for each first and last name in the json gets pushed in the format above?

Let's try this new game
use strict; use warnings;
use JSON::XS;
use Data::Dumper;
# creating reference to a void ARRAY
my $dummy_data = [];
# creating $json string
my $json = '{"d":{"success":true,"drivers":[{"FIRST_NAME":"JOHN","LAST_NAME":"SMITH"},{"FIRST_NAME":"JANE","LAST_NAME":"DOE"}]}}';
# converting JSON -> Perl data structure
my $perl_hash = decode_json $json;
# feeding $dummy_data ARRAY ref with a HASH
push #$dummy_data, {
name => $perl_hash->{d}->{drivers}->[0]->{FIRST_NAME},
key => $perl_hash->{d}->{drivers}->[1]->{FIRST_NAME}
};
# print what we have finally
print Dumper $dummy_data;
Output
$VAR1 = [
{
'name' => 'JOHN',
'key' => 'JANE'
}
];

Related

Perl: hash from import JSON data, Dumper Outputs right data, However I can not access it

I have the following data in .json; actual values substituted.
{ "Mercury": [
{
"Long": "0.xxxxxx",
"LongP": "0.xxxxx",
"Eccent": "0.xxxx",
"Semi": "0.xxxx",
"Inclin": "0.xxxx",
"ascnode": "0.xx.xxxx",
"adia": "0.xxx",
"visual": "-0.xx"
}
]
}
This works fine:
my %data = ();
my $json = JSON->new();
my $data = $json->decode($json_text);
my $planet = "Mercury";
print Dumper $data; # prints:
This is all fine:
$VAR1 = {
'Mercury' => [
{
'Inclin' => '7.',
'Semi' => '0.8',
'adia' => '6.7',
'LongP' => '77.29',
'visual' => '-0.00',
'Long' => '60.000',
'Eccent' => '0.0000',
'ascnode' => '48.0000'
}
]
};
However when I try to access the hash:
my $var = $data{$planet}{Long};
I get empty values, why?
Problem 1
$data{$planet} accesses hash %data, but you populated scalar $data.
You want $data->{$planet} instead of $data{$planet}.
Always use use strict; use warnings;. It would have caught this error.
Problem 2
$data->{$planet} returns a reference to an array.
You want $data->{$planet}[0]{Long} (first element) or $data->{$planet}[-1]{Long} (last element) instead of $data->{$planet}{Long}. Maybe. An array suggests the number of elements isn't always going to be one, so you might want a loop.

How to parse JSON/REST data from server using Perl

Im trying to parse out JSON output from the server using Perl. The connection and downloading of the REST data is ok, I just need help parsing the returned data. Here is the snippet for my code:
my $response = HTTP::Tiny->new->get($SERVER_ADDR);
if ($response->{success})
{
my $html = $response->{content};
#LINES = split /\n/, $html;
chomp(#LINES);
print("Lines: '#LINES'\n"); # ZZZ
my $decoded_json = decode_json( $html );
print Dumper $decoded_json;
}
else
{
print "Failed: $response->{status} $response->{reasons}";
}
And here is the results:
Lines: '{"players":[{"currentlyOnline":false,"timePlayed":160317,"name":"MarisaG","lastPlayed":1474208741470}]}'
$VAR1 = {
'players' => [
{
'currentlyOnline' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
'timePlayed' => 160317,
'lastPlayed' => '1474208741470',
'name' => 'MarisaG'
}
]
};
There will be multiple entries under the "players" for each player logged in right now. Any tips?
I'm not really sure what you're asking. You have successfully parsed the JSON by by calling decode_json(). You now have a data structure in $decoded_json. Your call to Dumper() shows the structure of that data. It's a hash reference with a single key, players. The value associated with that key is an array reference. Each element in the referenced array is another hash.
So, for example, you could print all of the players' names with code like this.
foreach (#{ $decoded_json->{players} }) {
say $_->{name};
}

Perl LWP returns JSON output as string

I am using Perl LWP::UserAgent to get response from an API. Everything works good except one issue.
The API that i am using it returns response in JSON format. But I am getting it as string when i get the response through LWP module, Something like below.
$VAR1 = '
{"status":"success","data":[{"empid":"345232","customername":"Lee gates","dynamicid":"2342342332sd32423"},{"empid":"36.VLXP.013727..CBCL..","customername":"Lee subdirectories","dynamicid":"223f3423dsf23423423"}],"message":""}'
I did "print Dumper $response" to get the output.
One more thing, The challenge is that my client do not want to go with Perl module for JSON (use JSON::Parse 'parse_json';).
Any help would be appreciated!
You need to decode the JSON string into a Perl data structure. If your version of perl is 5.14+, JSON::PP is included in core, so nothing to install.
use warnings;
use strict;
use Data::Dumper;
use JSON::PP qw(decode_json);
my $json = '{"status":"success","data":[{"empid":"345232","customername":"Lee gates","dynamicid":"2342342332sd32423"},{"empid":"36.VLXP.013727..CBCL..","customername":"Lee subdirectories","dynamicid":"223f3423dsf23423423"}],"message":""}';
my $perl = decode_json $json;
print Dumper $perl;
Output:
$VAR1 = {
'status' => 'success',
'message' => '',
'data' => [
{
'dynamicid' => '2342342332sd32423',
'customername' => 'Lee gates',
'empid' => '345232'
},
{
'empid' => '36.VLXP.013727..CBCL..',
'customername' => 'Lee subdirectories',
'dynamicid' => '223f3423dsf23423423'
}
]
};

JSON Data output

Below is the Perl code having JSON data:
use Data::Dumper;
use JSON;
my $var = '{
"episode1": {
"title":"Cartman Gets an Anal Probe",
"id":"103511",
"airdate":"08.13.97",
"episodenumber":"101",
"available":"true",
"when":"08.13.97"
}
},
{
"episode2": {
"title":"Weight Gain 4000",
"id":"103516",
"airdate":"08.20.97",
"episodenumber":"102",
"available":"true",
"when":"08.20.97"
}
}';
my $resp = JSON::jsonToObj( $var );
print Dumper ($resp);
The output is:
$VAR1 = {
'episode1' => {
'when' => '08.13.97',
'episodenumber' => '101',
'airdate' => '08.13.97',
'title' => 'Cartman Gets an Anal Probe',
'id' => '103511',
'available' => 'true'
}
};
I am dumping a JSON data but only episode1 is dumped in the output. But, I want both episode1 and episode2 to be displayed when I dump. How to do it?
Write valid JSON.
From JSON Lint
Parse error on line 14:
...: "08.13.97" }},{ "episode2":
---------------------^
Expecting 'EOF'
If you want an array of objects, you need an array in the data: [...].

create a json string in perl

I am trying to create a json string in perl that outputs something like this:
{"d":{"success":false, "error":"key is required"}}
I have figured out how to do it without the "d" using this example:
my %rec_hash = ('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
my $json = encode_json \%rec_hash;
print "$json\n";
but not sure what I'm suppose to do with the extra level
What you need is a hash reference:
use strict;
use warnings;
use JSON;
my $json = JSON->new;
my $data_to_json = {d=>{success=>JSON::false,error=>"key is required"}};
print $json->encode($data_to_json) . "\n";
The output is:
{"d":{"success":false,"error":"key is required"}}
Note the use of JSON::false to denote a value that the JSON module will correctly translate to false as a JSON value.