Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

json_query() is reordering arrays. #200

Closed
andysCaplin opened this issue Dec 13, 2019 · 4 comments
Closed

json_query() is reordering arrays. #200

andysCaplin opened this issue Dec 13, 2019 · 4 comments

Comments

@andysCaplin
Copy link

andysCaplin commented Dec 13, 2019

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());
}
@andysCaplin
Copy link
Author

Actually if I use [:2] instead of [0,1] I get the right answer but in the JSON path doc it doesn't mention that one method re-orders and the other doesn't.

@danielaparker
Copy link
Owner

Reopening, this is a defect. The re-ordering you see with [0,1] is a consequence of how jsoncons removes duplicates from unions, but it should preserve the order. Thanks for reporting this.

@danielaparker
Copy link
Owner

Fixed on master. You'll now see the expected [{"author":"C"},{"author":"B"}].

@danielaparker
Copy link
Owner

Fix is in Release 0.142.0.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants