Skip to content

json_query() is reordering arrays. #200

@andysCaplin

Description

@andysCaplin

When I call json_query() on an array it reorders the results. i.e if I have

JSON: {"book":[{"author":"C"},{"author":"B"},{"author":"A"}]}
query: $.book[0,1]
result [{"author":"B"},{"author":"C"}]

I get the correct contents but in the wrong order. I expected to get [{"author":"C"},{"author":"B"}]

Is there any way to make the query preserve the order ?

I wrote this code to test it ( I initially thought it may have been the print that was the issue )

char *jsonString = (char *)"{\"book\":[{\"author\":\"C\"},{\"author\":\"B\"},{\"author\":\"A\"}]}";
jsoncons::json_options print_options;

print_options.new_line_chars("");
print_options.indent_size(0);
print_options.spaces_around_comma(jsoncons::spaces_option::no_spaces);
print_options.spaces_around_colon(jsoncons::spaces_option::no_spaces);

try {
    jsoncons::json json = jsoncons::json::parse(jsonString);
    std::ostringstream ss;
    ss << jsoncons::pretty_print(json, print_options);
    printf("<%s>\n\n", ss.str().c_str());
    ss.str(std::string());

    jsoncons::json qjson = jsoncons::jsonpath::json_query(json, "$.book[0,1]");
    ss << jsoncons::pretty_print(qjson, print_options);
    printf("<%s>\n\n", ss.str().c_str());
    ss.str(std::string());

    jsoncons::json qqjson = jsoncons::jsonpath::json_query(qjson, "$[0]");
    ss << jsoncons::pretty_print(qqjson, print_options);
    printf("<%s>\n\n", ss.str().c_str());
    ss.str(std::string());
} catch (const jsoncons::jsonpatch::jsonpatch_error& e) {
    printf("<%s>\n", e.what());
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions