perlでJSON

らら
らら

はじめに

perlでJSONやるとき、いつも過去のやつ探すの面倒だから・・

おぼえがきで・・・

メモ1

parents.json


{
	"parents": [{
		"childs": [{
			"name" : "データ1",
			"src" : "data1.txt"
		}, {
			"name" : "データ2",
			"src" : "data2.txt"
		}
		]
	}
	]
}

上記のperlのコード


#!/usr/bin/perl
use JSON;
my $json;
local $/ = undef;
open my $fh, '<', 'parents.json';
$json = <$fh>;
close $fh;
my $decoded = decode_json($json);
foreach my $parents ( @{$decoded->{parents}} ) {
	foreach my $childs ( @{$parents->{childs}} ) {
		foreach my $elem ( sort ( keys ( %{$childs} ) ) ) {
			print $elem . "=" . $childs->{$elem} . "\n";
		}
		print "\n";
	}
}

メモ2

categories.json


{
	"categories": [{
			"name": "カテゴリ1",
			"key": "cat1",
			"files": [{
					"id": "id_a",
					"name": "a.jpg",
					"keywords": ["A, データA"]
				}, {
					"id": "id_b",
					"name": "b.jpg",
					"keywords": ["B, データB"]
				}
			]
		}, {
			"name": "カテゴリ2",
			"key": "cat2",
			"files": [{
					"id": "id_c",
					"name": "c.jpg",
					"keywords": ["C, データC"]
				}, {
					"id": "id_d",
					"name": "d.jpg",
					"keywords": ["D, データD"]
				}
			]
		}
	]
}

上記のperlのコード


#!/usr/bin/perl
use JSON;
my $json;
local $/ = undef;
open my $fh, '<', 'categories.json';
$json = <$fh>;
close $fh;
my $decoded = decode_json($json);
foreach my $categories ( @{$decoded->{categories}} ) {
	foreach my $cate ( sort ( keys ( %{$categories} ) ) ) {
		if(ref($categories->{$cate}) ne 'ARRAY' && ref($categories->{$cate}) ne 'HASH') {
			print $cate . "=" . $categories->{$cate} . "\n"
		}
	}
	foreach my $files ( @{$categories->{files}} ) {
		foreach my $elem ( sort ( keys ( %{$files} ) ) ) {
			if(ref($files->{$elem}) eq 'ARRAY') {
				print $elem . "=" . join(', ',@{$files->{$elem}}) . "\n";
			} else {
				print $elem . "=" . $files->{$elem} . "\n";
			}
		}
		print "\n";
	}
}

関連記事