Bootstrap FreeKB - Perl (Scripting) - Getting Started with JSON::Create
Perl (Scripting) - Getting Started with JSON::Create

Updated:   |  Perl (Scripting) articles

The JSON::Create module can be installed using cpan or cpanm.

cpanm JSON::Create

 

Let's say you want to create the following JSON.

{ 
 "foo": "Hello",
 "bar": "World"
}

 

Here is how you would create the JSON using JSON::Create.

#!/usr/bin/perl
use JSON::Create 'create_json','write_json';
use strict;
use warnings;

my %hash = ( foo => 'Hello', bar => 'World' );
print create_json (\%hash);

 

Or like this.

#!/usr/bin/perl
use JSON::Create;
use strict;
use warnings;

my $jc = JSON::Create->new();
my %hash = ( foo => 'Hello', bar => 'World' );

print $jc->run(\%hash);

 

Which should produce the following.

{"foo":"Hello","bar":"World"}

 

You will probably want to set indent to 1 so that the output is pretty.

my $jc = JSON::Create->new( indent => 1 );

 

Which should then return the following.

{
  "foo":"Hello",
  "bar":"World"
}

 

And here is how you would write the JSON to a file named example.json.

my $return_code = write_json ('example.json', \%hash);

if ($return_code eq "1") {
  print "Successfully called write_json \n";
}
else {
  print "Failed calling write_json. Return Code = $return_code. \n";
}

 

Be aware that even if indent is used, the content of example.json will be inline. The jq or python -m json.tool commands (on Linux) can be used to format the output.

cat example.json | jq

 

Let's say example.json contains the following.

{
  "foo":"Hello",
  "bar":"World"
}

 

Here is how you would update the "foo" key to contain a value of "Goodbye" using both the JSON::Parse and JSON::Create modules.

#!/usr/bin/perl
use JSON::Parse 'json_file_to_perl';
use JSON::Create 'write_json';
use strict;
use warnings;

my $json = json_file_to_perl( "example.json" );
$json->{foo} = "Goodbye";

my $jc = JSON::Create->new( sort => 1 );
my $return_code = write_json ( "example.json", $json );

if ($return_code eq "1") {
  print "Successfully called write_json \n";
}
else {
  print "Failed calling write_json. Return Code = $return_code. \n";
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 473a7e in the box below so that we can be sure you are a human.