Accessing parent level using Data::Visitor::Callback (Perl) -


this long-shot, there perl developers out there know data::visitor::callback?

i have complex data structure traversing. each time find hash has 'total' key, need build url. have of data need create these urls of data comes higher in structure.

i don't think can access levels above , makes impossible build urls. realised needed data higher structure.

if can't make data::visitor::callback work me, means rolling own traversal code - pain.

data traversing converted following json (the "count" keys renamed "total" part of conversion process):

[         {             "field": "field_name",             "value": "a",             "count": 647,             "pivot": [                 {                     "field": "field_name",                     "value": "b",                     "count": 618,                     "pivot": [                         {                             "field": "field_name",                             "value": "c1",                             "count": 572                         },                         {                             "field": "field_name",                             "value": "c2",                             "count": 266                         },                         {                             "field": "field_name",                             "value": "c3",                             "count": 237                         }                     ]                 },                 ... 

once deepest level (c), need both , b values in order construct urls.

because data::visitor::callback acting on each leaf independently, i'm not sure 'knows' in structure is.

all appreciated.

thanks.

given json posted in variable $json_string, following code uses recursion add parents children in hash key parent, way can access parents in code.

use strict; use warnings; use json;  $data = decode_json($json_string);  add_parent_to_children($_) @$data;  sub add_parent_to_children {   $node        = shift;   $parent      = shift;   $node->{parent} = $parent if $parent;   if ($node->{pivot}) {     add_parent_to_children($_, $node) @{$node->{pivot}};   } } 

demo:

my $c3 = $data->[0]{pivot}[0]{pivot}[2]; print "$c3->{value}\n";                 # prints c3 print "$c3->{parent}{value}\n";         # prints b print "$c3->{parent}{parent}{value}\n"; # prints 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -