in reply to Translate or morph hash keys to different names

You didn't tell us, if your data is nested or just flat.

Perl doesn't allow to change keys in place, you either need to copy to new a hash, or delete and recreate every single key to be transformed. If the hashes are nested you need to walk thru the tree.

If I were you I would just check if the JSON string has a pretty format which allows a simple regex to translate keys only.

update

proof of concept:

DB<100> use JSON DB<101> $hoH = { nested => { crossReference => 42, incidentAbstract => "st +ring" }, } DB<102> $str = (new JSON)->pretty(1)->encode($hoH) { "nested" : { "incidentAbstract" : "string", "crossReference" : "42" } } DB<103> %translate= ( 'crossReference' => 'cross_reference' , "incidentAbstract" => 'abstract', ) DB<104> $or_keys = join "|", keys %translate => "incidentAbstract|crossReference" DB<105> $str =~ s/^(\s+")($or_keys)("\s+:)/$1$translate{$2}$3/gm => 2 DB<106> $str { "nested" : { "abstract" : "string", "cross_reference" : "42" } }

of course this can also be done with Data::Dumper ...

Cheers Rolf

( addicted to the Perl Programming Language)

Replies are listed 'Best First'.
Re^2: Translate or morph hash keys to different names
by rmcgowan (Sexton) on Nov 06, 2013 at 20:53 UTC

    The data is nested. And I understand that keys can't be changed directly.

    The suggestion of changing things in the JSON string, before decoding, is good and makes a lot of sense.

    My primary concerns are that I had missed something, perhaps in the JSON modules, that could do this for me, or an existing other module to do the morphing, so I didn't need to write my own.

    Thanks for the suggestion.