Nested json to csv. #555
-
|
Hello, Are there approximate solutions close to this task? |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments
-
|
Could you give an example of a nested JSON source and how you would expect it to be mapped to CSV? |
Beta Was this translation helpful? Give feedback.
-
|
Thank you for your reply! Suppose, we have this source (testjson_nested.json): And here is how Python csvkit's utility in2csv does this conversion:
I've even seen a C++ code that did it as well (except for saving field ordering, what is very important to be). Thanks. |
Beta Was this translation helpful? Give feedback.
-
|
Thanks for the suggestion. We don't currently support that, but we'll take it as a feature request for a future version. |
Beta Was this translation helpful? Give feedback.
-
|
I've added support for nested json to csv on master. This includes two additional csv options,
Your example becomes: #include <jsoncons/json.hpp>
#include <jsoncons_ext/csv/csv.hpp>
namespace csv = jsoncons::csv;
int main()
{
std::string jtext = R"(
[
{
"text": "Chicago Reader",
"float": 1.0,
"datetime": "1971-01-01T04:14:00",
"boolean": true,
"nested": {
"time": "04:14:00",
"nested": {
"date": "1971-01-01",
"integer": 40
}
}
},
{
"text": "Chicago Sun-Times",
"float": 1.27,
"datetime": "1948-01-01T14:57:13",
"boolean": true,
"nested": {
"time": "14:57:13",
"nested": {
"date": "1948-01-01",
"integer": 63
}
}
}
]
)";
auto j = jsoncons::json::parse(jtext);
auto options = csv::csv_options{}
.flat(false);
std::string buf;
csv::encode_csv(j, buf, options);
std::cout << buf << "\n";
}Output: This is how to customize the column mapping, auto j = jsoncons::json::parse(jtext);
auto options = csv::csv_options{}
.flat(false)
.column_mapping({
{"/datetime","Timestamp"},
{"/text", "Newspaper"},
{"/nested/nested/integer","Count"}
});
std::string buf;
csv::encode_csv(j, buf, options);
std::cout << buf << "\n";Output: Any feedback appreciated. |
Beta Was this translation helpful? Give feedback.
-
|
Thank you very much! I'll try to return to this topic next week. Thanks. |
Beta Was this translation helpful? Give feedback.
-
|
Yes, having ojson instead of json and this new "flat" with value "false" does the job, which almost completely simulates Python's default behaviour. Awesome! |
Beta Was this translation helpful? Give feedback.
I've added support for nested json to csv on master. This includes two additional csv options,
true, for backwards compatibility.false, column names default to the JSONPointers identifying their location within each item.)Your example becomes: