Skip to content

Instantly share code, notes, and snippets.

@jordansissel
Created April 19, 2025 17:28
Show Gist options
  • Save jordansissel/761ddd7103ee17215afec100ca99828a to your computer and use it in GitHub Desktop.
Save jordansissel/761ddd7103ee17215afec100ca99828a to your computer and use it in GitHub Desktop.

Possibly the worst way to encode json in C?

% emcc example.c -o example.js -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE='$UTF8ToString,$stringToNewUTF8

% node example.js
JSON: {"name":"Captain Pants","id":0}
// Compile with emcc -s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE='$UTF8ToString,$stringToNewUTF8'
#include <stdio.h>
#include <emscripten.h>
int main() {
struct player {
char *name;
int id;
} foo;
foo.name = "Captain Pants";
foo.id = 0;
// Use JavaScript's JSON.stringify() to generate JSON into a char* for use in C.
const char *json = (const char *)EM_ASM_PTR({
return stringToNewUTF8(JSON.stringify({
name: UTF8ToString($0),
id: $1
}));
}, foo.name, foo.id);
printf("JSON: %s\n", json);
free((void *)json);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment