c - 如何在 jsonb C 函数中构建嵌套对象?
问题描述
我能够构建并返回一个简单的jsonb
对象,但我坚持尝试使用嵌套对象作为值。
例如,我想返回jsonb
对象:
{"one":1.0,"nest":{"a":1.0,"b":2.0}}
以下代码unknown type of jsonb container
专门在此行返回错误:
result.res = pushJsonbValue(&result.parseState, WJB_VALUE, &obj_val);
这是我当前的代码:
Datum
build_a_nested_object(PG_FUNCTION_ARGS)
{
Datum num_val;
JsonbInState result, nested_result;
JsonbValue key, val, obj_val;
memset(&result, 0, sizeof(JsonbInState));
result.res = pushJsonbValue(&result.parseState, WJB_BEGIN_OBJECT, NULL);
// first key
key.type = jbvString;
key.val.string.len = 3;
key.val.string.val = "one";
result.res = pushJsonbValue(&result.parseState, WJB_KEY, &key);
// first value
val.type = jbvNumeric;
num_val = DirectFunctionCall3(numeric_in, CStringGetDatum("1.0"), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1));
val.val.numeric = DatumGetNumeric(num_val);
result.res = pushJsonbValue(&result.parseState, WJB_VALUE, &val);
// Second key
key.type = jbvString;
key.val.string.len = 4;
key.val.string.val = "nest";
result.res = pushJsonbValue(&result.parseState, WJB_KEY, &key);
// Second value
memset(&nested_result, 0, sizeof(JsonbInState));
nested_result.res = pushJsonbValue(&nested_result.parseState, WJB_BEGIN_OBJECT, NULL);
// First nested key
key.type = jbvString;
key.val.string.len = 1;
key.val.string.val = "a";
nested_result.res = pushJsonbValue(&nested_result.parseState, WJB_KEY, &key);
// First nested value
val.type = jbvNumeric;
numd = DirectFunctionCall3(numeric_in, CStringGetDatum("1.0"), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1));
val.val.numeric = DatumGetNumeric(numd);
nested_result.res = pushJsonbValue(&nested_result.parseState, WJB_VALUE, &val);
// Second nested key
key.type = jbvString;
key.val.string.len = 1;
key.val.string.val = "b";
nested_result.res = pushJsonbValue(&nested_result.parseState, WJB_KEY, &key);
// Second nested value
val.type = jbvNumeric;
numd = DirectFunctionCall3(numeric_in, CStringGetDatum("2.0"), ObjectIdGetDatum(InvalidOid), Int32GetDatum(-1));
val.val.numeric = DatumGetNumeric(numd);
nested_result.res = pushJsonbValue(&nested_result.parseState, WJB_VALUE, &val);
nested_result.res = pushJsonbValue(&nested_result.parseState, WJB_END_OBJECT, NULL);
obj_val.type = jbvBinary;
obj_val.val.binary.data = JsonbValueToJsonb(nested_result.res);
result.res = pushJsonbValue(&result.parseState, WJB_VALUE, &obj_val);
result.res = pushJsonbValue(&result.parseState, WJB_END_OBJECT, NULL);
PG_RETURN_POINTER(JsonbValueToJsonb(result.res));
}
解决方案
推荐阅读
- java - Travis CI 构建失败 -Github
- r - 如何用 coxph 输出计算风险比
- c# - 如果变量在主方法之外,如何显示索引号
- java - Tomcat 8.5.31 在部署战争时卡住了
- apache-spark - 有两个相同 Spark 作业的实例来处理 Kafka 主题是否可行?
- mysql - 新的 MySQL Workbench 安装(不会连接到 root)Ubuntu 18.04
- laravel-5.6 - Laravel 5.6 自定义查询构建显示空结果
- python - Telnet 使用 python 示例不起作用
- haskell - Cabal 在哪里搜索“包括:...”中列出的文件?
- azure - GraphAPI如何在用户创建时添加身份验证联系信息