| 1 | use 5.010; |
| 2 | use JSON::MaybeXS; |
| 3 | use Scalar::Util qw[blessed]; |
| 4 | use lib "../lib"; |
| 5 | use JSON::Path; |
| 6 | |
| 7 | my $json = JSON::MaybeXS->new( pretty => 1 ); |
| 8 | my $object = $json->decode(<<'JSON'); |
| 9 | { |
| 10 | "store": { |
| 11 | "book": [ |
| 12 | { |
| 13 | "category": "reference", |
| 14 | "author": "Nigel Rees", |
| 15 | "title": "Sayings of the Century", |
| 16 | "price": 8.95 |
| 17 | }, |
| 18 | { |
| 19 | "category": "fiction", |
| 20 | "author": "Evelyn Waugh", |
| 21 | "title": "Sword of Honour", |
| 22 | "price": 12.99 |
| 23 | }, |
| 24 | { |
| 25 | "category": "fiction", |
| 26 | "author": "Herman Melville", |
| 27 | "title": "Moby Dick", |
| 28 | "isbn": "0-553-21311-3", |
| 29 | "price": 8.99 |
| 30 | }, |
| 31 | { |
| 32 | "category": "fiction", |
| 33 | "author": "J. R. R. Tolkien", |
| 34 | "title": "The Lord of the Rings", |
| 35 | "isbn": "0-395-19395-8", |
| 36 | "price": 22.99 |
| 37 | } |
| 38 | ], |
| 39 | "bicycle": { |
| 40 | "color": "red", |
| 41 | "price": 19.95 |
| 42 | } |
| 43 | } |
| 44 | } |
| 45 | JSON |
| 46 | |
| 47 | $JSON::Path::Safe = 0; |
| 48 | |
| 49 | foreach ('$.store.book[0].title', '$.store.book[*].author', '$..author', '$..book[-1:]', |
| 50 | '$..book[?($_->{author} =~ /tolkien/i)]') |
| 51 | { |
| 52 | my $jpath = JSON::Path->new($_); |
| 53 | say $jpath; |
| 54 | say $json->encode([$jpath->values($object)]); |
| 55 | say $json->encode([$jpath->paths($object)]); |
| 56 | say [$jpath->values($object)]->[0]->nodePath |
| 57 | if blessed([$jpath->values($object)]->[0]); |
| 58 | say '-' x 40; |
| 59 | } |