Skip to content

Instantly share code, notes, and snippets.

@msymt
Last active October 12, 2021 07:51
Show Gist options
  • Save msymt/fcc895f48adda2f55bc107e9145f42a0 to your computer and use it in GitHub Desktop.
Save msymt/fcc895f48adda2f55bc107e9145f42a0 to your computer and use it in GitHub Desktop.
janssonのexample
#include<stdio.h>
#include<stdlib.h>
#include<jansson.h>
void jansson_pack_stdout_free(json_t *root) {
char *out = json_dumps(root, JSON_ENCODE_ANY);
printf("out:%s\r\n", out);
free(root);
free(out);
}
void jansson_pack_test(void) {
json_t *root;
char *out;
/* Build an empty JSON object */
root = json_pack("{}");
jansson_pack_stdout_free(root);
/* Build the JSON object {"foo": 42, "bar": 7} */
root = json_pack("{sisi}", "foo", 42, "bar", 7);
jansson_pack_stdout_free(root);
/* Like above, ':', ',' and whitespace are ignored */
root = json_pack("{s:i, s:i}", "foo", 42, "bar", 7);
jansson_pack_stdout_free(root);
/* Build the JSON array [[1, 2], {"cool": true}] */
root = json_pack("[[i,i],{s:b}]", 1, 2, "cool", 1);
jansson_pack_stdout_free(root);
/* Build a string from a non-null terminated buffer */
char buffer[4] = {'t', 'e', 's', 't'};
root = json_pack("[s#]", buffer, 4);
jansson_pack_stdout_free(root);
/* Concatenate strings together to build the JSON string "foobarbaz" */
root = json_pack("s++", "foo", "bar", "baz");
jansson_pack_stdout_free(root);
/* Create an empty object or array when optional members are missing */
root = json_pack("s:s*,s:o*,s:0*", "foo", NULL, "bar", NULL, "baz", NULL);
jansson_pack_stdout_free(root);
root = json_pack("s*,o*,0*", NULL, NULL, NULL);
jansson_pack_stdout_free(root);
}
void jansson_decref_test() {
json_t *array, *integer;
array = json_array();
integer = json_integer(42);
char *out = json_dumps(array, JSON_ENCODE_ANY);
printf("out:%s\r\n", out);
free(out);
json_array_append(array, integer);
out = json_dumps(array, JSON_ENCODE_ANY);
printf("out:%s\r\n", out);
free(out);
out = json_dumps(integer, JSON_ENCODE_ANY);
printf("out:%s\r\n", out);
free(out);
// メモリ解放?
json_decref(integer);
}
int main(void){
jansson_pack_test();
puts("");
jansson_decref_test();
return 0;
}
/**
* $ brew install jansson
* $ gcc -ljansson -o jass jass.c
*/
/*
# output
out:{}
out:{"foo": 42, "bar": 7}
out:{"foo": 42, "bar": 7}
out:[[1, 2], {"cool": true}]
out:["test"]
out:"foobarbaz"
out:(null)
out:(null)
out:[]
out:[42]
out:42
out:[42]
out:42
*/
/**
* ref:
* https://jansson.readthedocs.io/en/latest/apiref.html#building-values
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment