mirror of
https://github.com/postgres/postgres.git
synced 2025-06-16 06:01:02 +03:00
json_typeof function.
Andrew Tipton.
This commit is contained in:
@ -1826,3 +1826,55 @@ escape_json(StringInfo buf, const char *str)
|
||||
}
|
||||
appendStringInfoCharMacro(buf, '\"');
|
||||
}
|
||||
|
||||
/*
|
||||
* SQL function json_typeof(json) -> text
|
||||
*
|
||||
* Returns the type of the outermost JSON value as TEXT. Possible types are
|
||||
* "object", "array", "string", "number", "boolean", and "null".
|
||||
*
|
||||
* Performs a single call to json_lex() to get the first token of the supplied
|
||||
* value. This initial token uniquely determines the value's type. As our
|
||||
* input must already have been validated by json_in() or json_recv(), the
|
||||
* initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
|
||||
* JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
|
||||
*/
|
||||
Datum
|
||||
json_typeof(PG_FUNCTION_ARGS)
|
||||
{
|
||||
text *json = PG_GETARG_TEXT_P(0);
|
||||
|
||||
JsonLexContext *lex = makeJsonLexContext(json, false);
|
||||
JsonTokenType tok;
|
||||
char *type;
|
||||
|
||||
/* Lex exactly one token from the input and check its type. */
|
||||
json_lex(lex);
|
||||
tok = lex_peek(lex);
|
||||
switch (tok)
|
||||
{
|
||||
case JSON_TOKEN_OBJECT_START:
|
||||
type = "object";
|
||||
break;
|
||||
case JSON_TOKEN_ARRAY_START:
|
||||
type = "array";
|
||||
break;
|
||||
case JSON_TOKEN_STRING:
|
||||
type = "string";
|
||||
break;
|
||||
case JSON_TOKEN_NUMBER:
|
||||
type = "number";
|
||||
break;
|
||||
case JSON_TOKEN_TRUE:
|
||||
case JSON_TOKEN_FALSE:
|
||||
type = "boolean";
|
||||
break;
|
||||
case JSON_TOKEN_NULL:
|
||||
type = "null";
|
||||
break;
|
||||
default:
|
||||
elog(ERROR, "unexpected json token: %d", tok);
|
||||
}
|
||||
|
||||
PG_RETURN_TEXT_P(cstring_to_text(type));
|
||||
}
|
||||
|
Reference in New Issue
Block a user