我使用三个脚本创建了一个示例。
第一个是创建列表,然后将其写入 JSON 文件的 Python 脚本。然后我们有一个 Perl 脚本,它读入 JSON,修改它(向数组添加另外三个元素),然后将它写回 JSON 数据文件。最后一个 Python 脚本展示了如何读取 JSON 并使用数据。
Python 脚本,创建一个列表,将其写入 json 文件
import json
data = [1, 2, 3]
with open('data.json', 'w') as jsonfile:
json.dump(data, jsonfile)
数据文件现在看起来像:
[1, 2, 3]
Perl 脚本,读取 JSON 文件,处理数据,将其写回:
use warnings;
use strict;
use JSON;
my $file = 'data.json';
# read in json from Python
my $json;
{
local $/;
open my $fh, '<', $file or die $!;
$json = <$fh>;
close $fh;
}
my $array = decode_json $json;
# modify the list (array)
push @$array, (4, 5, 6);
# re-encode the changed data, write it back to a json file
$json = encode_json $array;
open my $fh, '>', $file or die $!;
print $fh $json;
close $fh or die $!;
数据文件现在看起来像:
[1, 2, 3, 4, 5, 6]
Python 脚本,读取更新后的 JSON 文件,并将其转换回列表:
import json
file = 'data.json';
data = json.loads(open(file).read())
print(data)
打印:
[1, 2, 3, 4, 5, 6]