Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute python script and read its JSON output

Tags:

python

json

perl

I have a python script "/marvel/avengers.py" which returns following JSON array when executed.

#!/usr/bin/python3
X = [{"name":"tony", "job": "ironman"}, {"name": "banner", "job": "hulk"}]
print(X)

OUTPUT:

[{'name':'tony', 'job': 'ironman'}, {'name': 'banner', 'job': 'hulk'}]

I want to execute this python script from perl and read its JSON output. But I am getting JSON parsing errors. My perl code:

#!/usr/bin/perl
use strict;
use warnings;
use JSON;
my $json = `python /marvel/avengers.py`;
print Dumper($json);
my $parsed_json = JSON::decode_json($json);

OUTPUT:

$VAR1 = '[{\'job\': \'ironman\', \'name\': \'tony\'}, {\'job\': \'hulk\', \'name\': \'banner\'}]
';
'"' expected, at character offset 2 (before "'job': 'ironman', 'n...") at ./avengers_perl.pl line 7.
like image 506
PJ47 Avatar asked Aug 13 '26 18:08

PJ47


1 Answers

Python script was printing output in single quotes which was not JSON. Changing it to below fixed the issue.

#!/usr/bin/python3
import json
X = [{"name":"tony", "job": "ironman"}, {"name": "banner", "job": "hulk"}]
print(json.dumps(X), end='')

OUTPUT:

[{"job": "ironman", "name": "tony"}, {"job": "hulk", "name": "banner"}]
like image 87
PJ47 Avatar answered Aug 15 '26 08:08

PJ47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!