in reply to Converting boolean values in XMLout
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Converting boolean values in XMLout (code)
by ikegami (Patriarch) on Jun 22, 2009 at 19:21 UTC | |
It (at least) appears a bit simpler with recursion, although it's probably a bit slower.
| [reply] [d/l] [select] |
|
Re^2: Converting boolean values in XMLout
by pKai (Priest) on Jun 23, 2009 at 11:27 UTC | |
You'll need to walk the structure For which there is the fine Data::Rmap module:
Output:
| [reply] [d/l] [select] |
|
Re^2: Converting boolean values in XMLout
by Anonymous Monk on Jan 26, 2012 at 11:57 UTC | |
In case it's useful to someone out there, I found that Rmap as used in pKai's sample code, didn't recurse as I wanted it to, for some Json strings anyway. For instance, if you have a nested json object where some of the values in an object are the same (e.g. a list of keys with boolean values), decode_json uses JSON::true or JSON::false for the first instance it comes across, but then adds hash references to an existing true or false for all subsequent instances. This is presumably for performance? Whatever the reason, it caused me a bit of chin-scratching (not hard!). Consider the following string of Json, (which might have been received as a post parameter, say):
If I tried this in pKai's code above, you don't get the required result - XML::Simple still complains:
The Rmap docs state that if there are multiple routes to the same node, only the first will be followed... so I'm pretty sure this is working as designed, but it's just not what I needed... One way round it was just to repeat the same rmap_ref call against the object until there weren't any blessed objects left, but that seems dumb - it can't be very efficient? But it does work:
In the end, I used something similar to ikegami's code above to make sure I walk a nested structure fully, but instead of using 1 or 0 to substitute the blessed JSON booleans, I used references, so that I could 'round trip' the resulting object using encode_json and get proper json booleans at the client (rather than the integers 1 or 0).
There's probably a neat way to use Rmap to do the walking, but it was beyond my abilities I'm afraid. :( | [reply] [d/l] [select] |
by ikegami (Patriarch) on Jan 31, 2012 at 09:50 UTC | |
No, not quite. When JSON::XS is loaded, it creates two objects
No other instances are ever created. No references to those are created. Those two objects are used everywhere.
It's refusing to visit the same reference twice. You could probably mess with its seen method (which appears to be a way at peeking at the module's internals). | [reply] [d/l] [select] |
by perlyogi (Acolyte) on Sep 26, 2012 at 07:53 UTC | |
The exact code for perl to take into consideration multiple routes to the same node so that rmap_ref need not be called multiple times would be rmap_ref { $_[0]{seen} = {}; $_ = "$_" if JSON::is_bool($_) } $result; | [reply] [d/l] |