Skip to content

Instantly share code, notes, and snippets.

@trya
Created May 12, 2018 10:42
Show Gist options
  • Save trya/45799f64bdda3e031d64555d75dfc563 to your computer and use it in GitHub Desktop.
Save trya/45799f64bdda3e031d64555d75dfc563 to your computer and use it in GitHub Desktop.
JSON to S-expr
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include <json-c/json.h>
void json2sexp(struct json_object *jobj);
void json_array2sexp(struct json_object *jarray);
void json_obj2sexp(struct json_object *jobj);
void json_array2sexp(struct json_object *jarray)
{
size_t array_len;
array_len = json_object_array_length(jarray);
if (array_len > 0) {
json2sexp(json_object_array_get_idx(jarray, 0));
}
for (size_t i = 1; i < array_len; i++) {
printf(" ");
json2sexp(json_object_array_get_idx(jarray, i));
}
}
void json_obj2sexp(struct json_object *jobj)
{
struct json_object_iter iter;
json_object_object_foreachC(jobj, iter) {
printf("(%s ", iter.key);
json2sexp(iter.val);
printf(iter.entry->next ? ") " : ")");
}
}
void json2sexp(struct json_object *jobj)
{
switch (json_object_get_type(jobj)) {
case json_type_null:
printf("nil");
break;
case json_type_boolean:
printf(json_object_get_boolean(jobj) ? "" : "nil");
break;
case json_type_double:
printf("%lf", json_object_get_double(jobj));
break;
case json_type_int:
printf("%" PRId64, json_object_get_int64(jobj));
break;
case json_type_string:
printf("\"%s\"", json_object_get_string(jobj));
break;
case json_type_object:
json_obj2sexp(jobj);
break;
case json_type_array:
json_array2sexp(jobj);
break;
}
}
int main(void)
{
char buf[65536];
ssize_t nb_read;
json_object *jobj;
enum json_tokener_error jerr;
struct json_tokener *jtok;
jtok = json_tokener_new();
while (1) {
jerr = json_tokener_continue;
while ((jerr == json_tokener_continue) &&
(nb_read = read(STDIN_FILENO, &buf, 65536)) > 0) {
jobj = json_tokener_parse_ex(jtok, buf, nb_read);
jerr = json_tokener_get_error(jtok);
}
if (nb_read < 0) {
perror("read");
exit(EXIT_FAILURE);
}
if (nb_read == 0) {
fprintf(stderr, "EOF reached\n");
exit(EXIT_SUCCESS);
}
if (jerr != json_tokener_success) {
fprintf(stderr, "json error: %s\n", json_tokener_error_desc(jerr));
exit(EXIT_FAILURE);
}
fprintf(stderr, "%s\n", json_object_to_json_string(jobj));
json2sexp(jobj); putchar('\n');
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment