danielaparker / jsoncons

A C++, header-only library for constructing JSON and JSON-like data formats, with JSON Pointer, JSON Patch, JSON Schema, JSONPath, JMESPath, CSV, MessagePack, CBOR, BSON, UBJSON
https://danielaparker.github.io/jsoncons
Other
700 stars 158 forks source link

add pretty_print to jsoncons::array() #533

Closed amassalha closed 1 month ago

amassalha commented 1 month ago

This code compilation fails:

#include <jsoncons/json.hpp>
#include <jsoncons/pretty_print.hpp>
#include <fstream>

int main() {
    // Create a JSON array with explicit type
    **auto** json_array = jsoncons::json::array();
    json_array.push_back("value1");
    json_array.push_back(42);
    json_array.push_back(jsoncons::json::object({{"key", "value"}}));

    // Specify the file name
    std::string filename = "/tmp/output.json";

    // Open the file for writing
    std::ofstream outfile(filename);
    if (!outfile) {
        std::cerr << "Error opening file for writing: " << filename << std::endl;
        return 1;
    }

    // Serialize and pretty-print the JSON array to the file
    outfile << jsoncons::pretty_print(json_array);

    // Close the file
    outfile.close();

    return 0;
}

but when I change 'auto' with jsoncons::json, it works. seems array is not a json:

#include <jsoncons/json.hpp>

int main() {
    // Create a JSON array
    auto json_array = jsoncons::json::array();

    // Use static_assert to ensure the type is what you expect
    static_assert(std::is_same_v<decltype(json_array), jsoncons::json>, "Type of json_array is not jsoncons::json");

    return 0;
}

err:
'jsoncons::json_array<jsoncons::basic_json<char>>'`)
` error: static assertion failed due to requirement 'std::is_same_v<jsoncons::json_array<jsoncons::basic_json<char, jsoncons::sorted_policy, std::allocator<char>>, std::vector>, jsoncons::basic_json<char, jsoncons::sorted_policy, std::allocator<char>>>': Type of json_array is not jsoncons::json
  745 |   static_assert(std::is_same_v<decltype(json_array), jsoncons::json>, "Type of json_array is not jsoncons::json");`
danielaparker commented 1 month ago

Apologies for the delay, just getting to this one.

jsoncons::json json_array = jsoncons::json::array();

is roughly equivalent to (the preferred)

jsoncons::json json_array{jsoncons::json_array_arg};

If you really want to use a json::array directly rather than through a json, I would suggest writing that as

auto json_array = jsoncons::json::array();
json_array.push_back("value1");
json_array.push_back(42);
json_array.push_back(jsoncons::json::object({ {"key", "value"} }));
jsoncons::json json{ std::move(json_array)}; // move to avoid copying

std::ofstream outfile(filename);
outfile << jsoncons::pretty_print(json);

A json::array is not a json, but is copyable and movable into a json. json::array and json::object are really implementation detail for json.