Skip to content

json with preserve_order_policy does not preserve order of elements #210

@jkalmar

Description

@jkalmar

We use ojson with multiple levels of objects that we then fill with data in code and want to pretty-print them, but the data are printed in reverse order:
Example code:

   jsoncons::ojson oj;

   oj[ "1" ][ "1" ][ "1" ] = 1;
   oj[ "1" ][ "1" ][ "2" ] = 1;
   oj[ "1" ][ "2" ][ "1" ] = 2;
   oj[ "1" ][ "2" ][ "2" ] = 2;
   oj[ "1" ][ "3" ][ "1" ] = 3;
   oj[ "1" ][ "3" ][ "2" ] = 3;

   oj[ "2" ][ "1" ][ "1" ] = 1;
   oj[ "2" ][ "1" ][ "2" ] = 1;
   oj[ "2" ][ "2" ][ "1" ] = 2;
   oj[ "2" ][ "2" ][ "2" ] = 2;
   oj[ "2" ][ "3" ][ "1" ] = 3;
   oj[ "2" ][ "3" ][ "2" ] = 3;

   std::cout << jsoncons::pretty_print( oj ) << std::endl;

The result is:

{
    "2": {
        "3": {
            "1": 3, 
            "2": 3
        }, 
        "2": {
            "1": 2, 
            "2": 2
        }, 
        "1": {
            "1": 1, 
            "2": 1
        }
    }, 
    "1": {
        "3": {
            "1": 3, 
            "2": 3
        }, 
        "2": {
            "1": 2, 
            "2": 2
        }, 
        "1": {
            "1": 1, 
            "2": 1
        }
    }
}

As you can see the first and second level keys are reversed, only the third level element order is preserved.
I have also tried to first create the upper levels but the output was the same:

   oj[ "1" ];
   oj[ "2" ];

   oj[ "1" ][ "1" ];
   oj[ "1" ][ "2" ];
   oj[ "1" ][ "3" ];

   oj[ "1" ][ "1" ][ "1" ] = 1;
   oj[ "1" ][ "1" ][ "2" ] = 1;
   oj[ "1" ][ "2" ][ "1" ] = 2;
   oj[ "1" ][ "2" ][ "2" ] = 2;
   oj[ "1" ][ "3" ][ "1" ] = 3;
   oj[ "1" ][ "3" ][ "2" ] = 3;

   oj[ "2" ];
   oj[ "2" ];

   oj[ "2" ][ "1" ];
   oj[ "2" ][ "2" ];
   oj[ "2" ][ "3" ];


   oj[ "2" ][ "1" ][ "1" ] = 1;
   oj[ "2" ][ "1" ][ "2" ] = 1;
   oj[ "2" ][ "2" ][ "1" ] = 2;
   oj[ "2" ][ "2" ][ "2" ] = 2;
   oj[ "2" ][ "3" ][ "1" ] = 3;
   oj[ "2" ][ "3" ][ "2" ] = 3;

Is this how it should work?
What I expected from ojson is to preserve the order of all elements, but it seem that it does not do it.
Can you please check it and help?
I use jsoncons from git master commit c4a77de

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions