首页 > 解决方案 > 如何在 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));

}

标签: cpostgresqljsonb

解决方案


推荐阅读