Skip to content

Instantly share code, notes, and snippets.

@spytheman
Created July 20, 2022 18:37
Show Gist options
  • Save spytheman/85acb0139a8c61ca7dd5fa76721c114f to your computer and use it in GitHub Desktop.
Save spytheman/85acb0139a8c61ca7dd5fa76721c114f to your computer and use it in GitHub Desktop.
How to encode a JSON result, that has null for some of the fields.
module main
import json
pub type Node = C.cJSON
struct UseJson {
x int
}
fn suppress_json_warning() {
json.encode(UseJson{})
}
fn C.cJSON_CreateObject() &C.cJSON
fn C.cJSON_CreateArray() &C.cJSON
fn C.cJSON_CreateBool(bool) &C.cJSON
fn C.cJSON_CreateTrue() &C.cJSON
fn C.cJSON_CreateFalse() &C.cJSON
fn C.cJSON_CreateNull() &C.cJSON
fn C.cJSON_CreateNumber() &C.cJSON
fn C.cJSON_CreateString() &C.cJSON
fn C.cJSON_CreateRaw(&u8) &C.cJSON
fn C.cJSON_IsInvalid(voidptr) bool
fn C.cJSON_IsFalse(voidptr) bool
fn C.cJSON_IsTrue(voidptr) bool
fn C.cJSON_IsBool(voidptr) bool
fn C.cJSON_IsNull(voidptr) bool
fn C.cJSON_IsNumber(voidptr) bool
fn C.cJSON_IsString(voidptr) bool
fn C.cJSON_IsArray(voidptr) bool
fn C.cJSON_IsObject(voidptr) bool
fn C.cJSON_IsRaw(voidptr) bool
fn C.cJSON_AddItemToObject(voidptr, &u8, voidptr)
fn C.cJSON_AddItemToArray(voidptr, voidptr)
fn C.cJSON_Delete(voidptr)
fn C.cJSON_Print(voidptr) &u8
fn create_object() &C.cJSON {
return C.cJSON_CreateObject()
}
fn create_array() &C.cJSON {
return C.cJSON_CreateArray()
}
fn create_string(val string) &C.cJSON {
return C.cJSON_CreateString(val.str)
}
fn create_number(val f64) &C.cJSON {
return C.cJSON_CreateNumber(val)
}
fn create_bool(val bool) &C.cJSON {
return C.cJSON_CreateBool(val)
}
fn create_true() &C.cJSON {
return C.cJSON_CreateTrue()
}
fn create_false() &C.cJSON {
return C.cJSON_CreateFalse()
}
fn create_null() &C.cJSON {
return C.cJSON_CreateNull()
}
fn delete(b voidptr) {
C.cJSON_Delete(b)
}
fn add_item_to_object(obj &C.cJSON, key string, item &C.cJSON) {
C.cJSON_AddItemToObject(obj, key.str, item)
}
fn add_item_to_array(obj &C.cJSON, item &C.cJSON) {
C.cJSON_AddItemToArray(obj, item)
}
fn json_print(json &C.cJSON) string {
mut s := C.cJSON_PrintUnformatted(json)
return unsafe { tos3(s) }
}
fn main() {
mut root := create_object()
add_item_to_object(root, 'name', create_string('Andre'))
add_item_to_object(root, 'age', create_null())
s := json_print(root)
dump(s)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment