Created
August 17, 2015 06:43
-
-
Save kimburgess/3e1f1496aa1c14d6dfd2 to your computer and use it in GitHub Desktop.
Rudimentary library for building string representations of flat JSON objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Rudimentary library for building string representations of flat JSON objects. | |
*/ | |
program_name='json-builder' | |
#if_not_defined __JSON_BUILDER_ | |
#define __JSON_BUILDER_ | |
define_constant | |
integer JSON_MAX_RETURN_SIZE = 4096 | |
integer JSON_MAX_KEY_SIZE = 256 | |
integer JSON_MAX_VALUE_SIZE = 1024 | |
define_type | |
structure json_item { | |
char key[JSON_MAX_KEY_SIZE] | |
char value[JSON_MAX_VALUE_SIZE] | |
} | |
define_function integer json_set_str(json_item json[], char key[], char value[]) { | |
// TODO escape quote characters within the string | |
return json_set_value(json, key, "'"', value, '"'") | |
} | |
define_function integer json_set_int(json_item json[], char key[], long value) { | |
return json_set_value(json, key, itoa(value)) | |
} | |
define_function integer json_set_double(json_item json[], char key[], double value) { | |
return json_set_value(json, key, ftoa(value)) | |
} | |
define_function integer json_set_bool(json_item json[], char key[], char value) { | |
if (value == true) { | |
return json_set_value(json, key, 'true') | |
} else { | |
return json_set_value(json, key, 'false') | |
} | |
} | |
define_function integer json_set_null(json_item json[], char key[]) { | |
return json_set_value(json, key, 'null') | |
} | |
/** | |
* Sets a value within a json item array. If the key does not exist it is added. | |
*/ | |
define_function integer json_set_value(json_item json[], char key[], char value[]) { | |
stack_var integer i | |
for (i = 1; i <= max_length_array(json); i++) { | |
if (json[i].key == key || json[i].key == '') { | |
json[i].key = key | |
json[i].value = value | |
return i | |
} | |
} | |
return 0 | |
} | |
/** | |
* Turns an array of key/value pairs into its appropriate JSON string | |
* representation. | |
*/ | |
define_function char[JSON_MAX_RETURN_SIZE] json_stringify(json_item json[]) { | |
stack_var char r[JSON_MAX_RETURN_SIZE] | |
stack_var integer i | |
r = '{ ' | |
for (i = 1; i <= max_length_array(json); i++) { | |
if (json[i].key == '') { | |
break | |
} | |
r = "r, '"', json[i].key, '": ', json[i].value, ', '" | |
} | |
if (r == '{ ') { | |
r = '{}' | |
} else { | |
r = "left_string(r, length_string(r) - 2), ' }'" | |
} | |
return r | |
} | |
#end_if | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment