Skip to content

json_writer emits invalid JSON for string vectors (elements unquoted, last element unescaped) #3424

Description

@sims1253

void write(const std::string& key, const std::vector<std::string>& values) {

write(key, const std::vector<std::string>&) writes elements without surrounding quotes, and the final write bypasses process_string

*output_ << values.back() << " ]";

stan::callbacks::json_writer<std::stringstream> w(std::move(owned));
w.begin_record();
w.write("quoted", std::vector<std::string>{"a\"b", "c\"d"});
w.end_record();
// output: "quoted" : [ a\"b, c"d ]

Gives invalid JSON for ordinary input. The final write also sits outside the if (values.size() > 0) guard the int overload has the same shape so an empty vector hits values.back() on an empty vector. The double overload keeps its final write inside the guard.

void write(const std::string& key, const std::vector<int>& values) {
if (output_ == nullptr) {
return;
}
write_sep();
write_key(key);
*output_ << "[ ";
if (values.size() > 0) {
auto last = values.end();
--last;
for (auto it = values.begin(); it != last; ++it) {
*output_ << *it << ", ";
}
}
*output_ << values.back() << " ]";
}

*output_ << values.back() << " ]";

void write(const std::string& key, const std::vector<double>& values) {
if (output_ == nullptr) {
return;
}
write_sep();
write_key(key);
*output_ << "[ ";
if (values.size() > 0) {
auto last = values.end();
--last;
for (auto it = values.begin(); it != last; ++it) {
write_value(*it);
*output_ << ", ";
}
write_value(values.back());

Probably just needs to mirror the double overload and quote and escape string elements including the last.

Environment:

  • Ubuntu 22.04.5 LTS (WSL2, kernel 6.18.33.2-microsoft-standard-WSL2), x86_64
  • stan-dev/stan develop @ 8ad5c98
  • g++ 11.4.0 (Ubuntu 22.04), -std=c++17

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions