Are you absolutely committed to relying on JSON objects preserving order? If your design mandates that to be the case, you would be better off making your filtered element contain an array of objects rather than object elements. This is a problem that my be solved by one level of indirection.

If there is any possibility that you can annul your marriage to a design that requires ordered JSON objects, I think you should give that possibility due consideration.

Here are a few reasons why:

Perl's hashes have a high degree of parity with JSON objects. Standard Perl hashes do not maintain any concept of static order. You can tie a Perl hash to a class that maintains order, but in doing so you make tradeoffs, giving away speed and memory for reliable ordering. Is it worth the tradeoff? If so, you may need to also rethink the serialization format you are using, because JSON isn't guaranteed to serialize and deserialize objects in any particular order. Any guarantees would have to come from the implementation. As an example, JSON parsers such as JSON::XS allow you to specify canonical ordering for object keys. But canonical is used to mean a sorted order. Not a user-specified order.


Dave


In reply to Re: Maintainance of element order in hash by davido
in thread Maintainance of element order in hash by ravi45722

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.