Reputation: 2881
Does FlatBuffer allow to convert a binary fbs file to and from JSON (of course the schema will be known)?
My idea is to define the schema of structures for a pipe&filter architecture in FlatBuffer. The FlatBuffer files will also be exchanged between pipes. However, some tools within some of the filters will require me to pass plain old json objects, converted from the FlatBuffer files. And I have several languages to support (C++, Python, Java, JS).
I've found a javascript library which seems to do this: https://github.com/evanw/node-flatbuffers/
But it seems abdondened and I'm rather interested in officially supported ways.
Upvotes: 4
Views: 8159
Reputation: 41
It is easy to convert flatbuffer buffer to JSON using Flat C version (FlatCC).
Please refer the sample tests in flatcc source path: flatcc-master/test/json_test.
Generate required json helper headers files using:
flatcc_d -a --json <yourData.fbs>
It will generate yourData_json_printer.h. Include this header file in your program.
Modify the below code to fit <yourData>
. buffer is your flatbuffer input received from other end.
Also do not use sizeof() to get bufferSize from buffer for flatbuffer. Print the buffersize before calling this
function
void flatbufToJson(const char *buffer, size_t bufferSize) {
flatcc_json_printer_t ctx_obj, *ctx;
FILE *fp = 0;
const char *target_filename = "yourData.json";
ctx = &ctx_obj;
fp = fopen(target_filename, "wb");
if (!fp) {
fprintf(stderr, "%s: could not open output file\n", target_filename);
printf("ctx not ready for clenaup, so exit directly\n");
return;
}
flatcc_json_printer_init(ctx, fp);
flatcc_json_printer_set_force_default(ctx, 1);
/* Uses same formatting as golden reference file. */
flatcc_json_printer_set_nonstrict(ctx);
//Check and modify here...
//the following should be re-written based on your fbs file and generated header file.
<yourData>_print_json(ctx, buffer, bufferSize);
flatcc_json_printer_flush(ctx);
if (flatcc_json_printer_get_error(ctx)) {
printf("could not print data\n");
}
fclose(fp);
printf("######### Json is done: \n");
}
Upvotes: 3
Reputation: 6074
Only C++ provides this functionality out of the box.
For other languages, you can wrap the C++ parser/generator, and call it (see e.g. for Java: http://frogermcs.github.io/json-parsing-with-flatbuffers-in-android/).
@evanw is the original author of the JS port in FlatBuffers, so the project you mention may be usable, but I don't think he's actively maintaining it anymore.
Alternatively, if this runs on a server and you can run command-line utilities, you can use the flatc
binary to do the conversion for you via a file.
Ideally, all languages would have their own native parser, but that is a lot of work to duplicate. While interfacing with C/C++ is a pain, it has the advantage of giving you a really fast parser.
Upvotes: 3