1 /*-------------------------------------------------------------------------
4 * JSON data type support.
6 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
10 * src/backend/utils/adt/json.c
12 *-------------------------------------------------------------------------
16 #include "access/htup_details.h"
17 #include "access/transam.h"
18 #include "catalog/pg_cast.h"
19 #include "catalog/pg_type.h"
20 #include "executor/spi.h"
21 #include "lib/stringinfo.h"
22 #include "libpq/pqformat.h"
23 #include "mb/pg_wchar.h"
24 #include "miscadmin.h"
25 #include "parser/parse_coerce.h"
26 #include "utils/array.h"
27 #include "utils/builtins.h"
28 #include "utils/datetime.h"
29 #include "utils/lsyscache.h"
30 #include "utils/json.h"
31 #include "utils/jsonapi.h"
32 #include "utils/typcache.h"
33 #include "utils/syscache.h"
36 * The context of the parser is maintained by the recursive descent
37 * mechanism, but is passed explicitly to the error reporting routine
38 * for better diagnostics.
40 typedef enum /* contexts of JSON parser */
42 JSON_PARSE_VALUE, /* expecting a value */
43 JSON_PARSE_STRING, /* expecting a string (for a field name) */
44 JSON_PARSE_ARRAY_START, /* saw '[', expecting value or ']' */
45 JSON_PARSE_ARRAY_NEXT, /* saw array element, expecting ',' or ']' */
46 JSON_PARSE_OBJECT_START, /* saw '{', expecting label or '}' */
47 JSON_PARSE_OBJECT_LABEL, /* saw object label, expecting ':' */
48 JSON_PARSE_OBJECT_NEXT, /* saw object value, expecting ',' or '}' */
49 JSON_PARSE_OBJECT_COMMA, /* saw object ',', expecting next label */
50 JSON_PARSE_END /* saw the end of a document, expect nothing */
53 typedef enum /* type categories for datum_to_json */
55 JSONTYPE_NULL, /* null, so we didn't bother to identify */
56 JSONTYPE_BOOL, /* boolean (built-in types only) */
57 JSONTYPE_NUMERIC, /* numeric (ditto) */
58 JSONTYPE_TIMESTAMP, /* we use special formatting for timestamp */
59 JSONTYPE_TIMESTAMPTZ, /* ... and timestamptz */
60 JSONTYPE_JSON, /* JSON itself (and JSONB) */
61 JSONTYPE_ARRAY, /* array */
62 JSONTYPE_COMPOSITE, /* composite */
63 JSONTYPE_CAST, /* something with an explicit cast to JSON */
64 JSONTYPE_OTHER /* all else */
67 static inline void json_lex(JsonLexContext *lex);
68 static inline void json_lex_string(JsonLexContext *lex);
69 static inline void json_lex_number(JsonLexContext *lex, char *s, bool *num_err);
70 static inline void parse_scalar(JsonLexContext *lex, JsonSemAction *sem);
71 static void parse_object_field(JsonLexContext *lex, JsonSemAction *sem);
72 static void parse_object(JsonLexContext *lex, JsonSemAction *sem);
73 static void parse_array_element(JsonLexContext *lex, JsonSemAction *sem);
74 static void parse_array(JsonLexContext *lex, JsonSemAction *sem);
75 static void report_parse_error(JsonParseContext ctx, JsonLexContext *lex);
76 static void report_invalid_token(JsonLexContext *lex);
77 static int report_json_context(JsonLexContext *lex);
78 static char *extract_mb_char(char *s);
79 static void composite_to_json(Datum composite, StringInfo result,
81 static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
82 Datum *vals, bool *nulls, int *valcount,
83 JsonTypeCategory tcategory, Oid outfuncoid,
85 static void array_to_json_internal(Datum array, StringInfo result,
87 static void json_categorize_type(Oid typoid,
88 JsonTypeCategory *tcategory,
90 static void datum_to_json(Datum val, bool is_null, StringInfo result,
91 JsonTypeCategory tcategory, Oid outfuncoid,
93 static void add_json(Datum val, bool is_null, StringInfo result,
94 Oid val_type, bool key_scalar);
96 /* the null action object used for pure validation */
97 static JsonSemAction nullSemAction =
99 NULL, NULL, NULL, NULL, NULL,
100 NULL, NULL, NULL, NULL, NULL
103 /* Recursive Descent parser support routines */
108 * what is the current look_ahead token?
110 static inline JsonTokenType
111 lex_peek(JsonLexContext *lex)
113 return lex->token_type;
119 * accept the look_ahead token and move the lexer to the next token if the
120 * look_ahead token matches the token parameter. In that case, and if required,
121 * also hand back the de-escaped lexeme.
123 * returns true if the token matched, false otherwise.
126 lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
128 if (lex->token_type == token)
132 if (lex->token_type == JSON_TOKEN_STRING)
134 if (lex->strval != NULL)
135 *lexeme = pstrdup(lex->strval->data);
139 int len = (lex->token_terminator - lex->token_start);
140 char *tokstr = palloc(len + 1);
142 memcpy(tokstr, lex->token_start, len);
156 * move the lexer to the next token if the current look_ahead token matches
157 * the parameter token. Otherwise, report an error.
160 lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
162 if (!lex_accept(lex, token, NULL))
163 report_parse_error(ctx, lex);;
166 /* chars to consider as part of an alphanumeric token */
167 #define JSON_ALPHANUMERIC_CHAR(c) \
168 (((c) >= 'a' && (c) <= 'z') || \
169 ((c) >= 'A' && (c) <= 'Z') || \
170 ((c) >= '0' && (c) <= '9') || \
178 json_in(PG_FUNCTION_ARGS)
180 char *json = PG_GETARG_CSTRING(0);
181 text *result = cstring_to_text(json);
185 lex = makeJsonLexContext(result, false);
186 pg_parse_json(lex, &nullSemAction);
188 /* Internal representation is the same as text, for now */
189 PG_RETURN_TEXT_P(result);
196 json_out(PG_FUNCTION_ARGS)
198 /* we needn't detoast because text_to_cstring will handle that */
199 Datum txt = PG_GETARG_DATUM(0);
201 PG_RETURN_CSTRING(TextDatumGetCString(txt));
208 json_send(PG_FUNCTION_ARGS)
210 text *t = PG_GETARG_TEXT_PP(0);
213 pq_begintypsend(&buf);
214 pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
215 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
222 json_recv(PG_FUNCTION_ARGS)
224 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
229 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
232 lex = makeJsonLexContextCstringLen(str, nbytes, false);
233 pg_parse_json(lex, &nullSemAction);
235 PG_RETURN_TEXT_P(cstring_to_text_with_len(str, nbytes));
241 * lex constructor, with or without StringInfo object
242 * for de-escaped lexemes.
244 * Without is better as it makes the processing faster, so only make one
245 * if really required.
247 * If you already have the json as a text* value, use the first of these
248 * functions, otherwise use makeJsonLexContextCstringLen().
251 makeJsonLexContext(text *json, bool need_escapes)
253 return makeJsonLexContextCstringLen(VARDATA(json),
254 VARSIZE(json) - VARHDRSZ,
259 makeJsonLexContextCstringLen(char *json, int len, bool need_escapes)
261 JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
263 lex->input = lex->token_terminator = lex->line_start = json;
264 lex->line_number = 1;
265 lex->input_length = len;
267 lex->strval = makeStringInfo();
274 * Publicly visible entry point for the JSON parser.
276 * lex is a lexing context, set up for the json to be processed by calling
277 * makeJsonLexContext(). sem is a strucure of function pointers to semantic
278 * action routines to be called at appropriate spots during parsing, and a
279 * pointer to a state object to be passed to those routines.
282 pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
286 /* get the initial token */
291 /* parse by recursive descent */
294 case JSON_TOKEN_OBJECT_START:
295 parse_object(lex, sem);
297 case JSON_TOKEN_ARRAY_START:
298 parse_array(lex, sem);
301 parse_scalar(lex, sem); /* json can be a bare scalar */
304 lex_expect(JSON_PARSE_END, lex, JSON_TOKEN_END);
309 * Recursive Descent parse routines. There is one for each structural
310 * element in a json document:
311 * - scalar (string, number, true, false, null)
318 parse_scalar(JsonLexContext *lex, JsonSemAction *sem)
321 json_scalar_action sfunc = sem->scalar;
323 JsonTokenType tok = lex_peek(lex);
325 valaddr = sfunc == NULL ? NULL : &val;
327 /* a scalar must be a string, a number, true, false, or null */
330 case JSON_TOKEN_TRUE:
331 lex_accept(lex, JSON_TOKEN_TRUE, valaddr);
333 case JSON_TOKEN_FALSE:
334 lex_accept(lex, JSON_TOKEN_FALSE, valaddr);
336 case JSON_TOKEN_NULL:
337 lex_accept(lex, JSON_TOKEN_NULL, valaddr);
339 case JSON_TOKEN_NUMBER:
340 lex_accept(lex, JSON_TOKEN_NUMBER, valaddr);
342 case JSON_TOKEN_STRING:
343 lex_accept(lex, JSON_TOKEN_STRING, valaddr);
346 report_parse_error(JSON_PARSE_VALUE, lex);
350 (*sfunc) (sem->semstate, val, tok);
354 parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
357 * an object field is "fieldname" : value where value can be a scalar,
361 char *fname = NULL; /* keep compiler quiet */
362 json_ofield_action ostart = sem->object_field_start;
363 json_ofield_action oend = sem->object_field_end;
365 char **fnameaddr = NULL;
368 if (ostart != NULL || oend != NULL)
371 if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
372 report_parse_error(JSON_PARSE_STRING, lex);
374 lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
377 isnull = tok == JSON_TOKEN_NULL;
380 (*ostart) (sem->semstate, fname, isnull);
384 case JSON_TOKEN_OBJECT_START:
385 parse_object(lex, sem);
387 case JSON_TOKEN_ARRAY_START:
388 parse_array(lex, sem);
391 parse_scalar(lex, sem);
395 (*oend) (sem->semstate, fname, isnull);
399 parse_object(JsonLexContext *lex, JsonSemAction *sem)
402 * an object is a possibly empty sequence of object fields, separated by
403 * commas and surrounded by curly braces.
405 json_struct_action ostart = sem->object_start;
406 json_struct_action oend = sem->object_end;
410 (*ostart) (sem->semstate);
413 * Data inside an object is at a higher nesting level than the object
414 * itself. Note that we increment this after we call the semantic routine
415 * for the object start and restore it before we call the routine for the
420 /* we know this will succeeed, just clearing the token */
421 lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
426 case JSON_TOKEN_STRING:
427 parse_object_field(lex, sem);
428 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
429 parse_object_field(lex, sem);
431 case JSON_TOKEN_OBJECT_END:
434 /* case of an invalid initial token inside the object */
435 report_parse_error(JSON_PARSE_OBJECT_START, lex);
438 lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
443 (*oend) (sem->semstate);
447 parse_array_element(JsonLexContext *lex, JsonSemAction *sem)
449 json_aelem_action astart = sem->array_element_start;
450 json_aelem_action aend = sem->array_element_end;
451 JsonTokenType tok = lex_peek(lex);
455 isnull = tok == JSON_TOKEN_NULL;
458 (*astart) (sem->semstate, isnull);
460 /* an array element is any object, array or scalar */
463 case JSON_TOKEN_OBJECT_START:
464 parse_object(lex, sem);
466 case JSON_TOKEN_ARRAY_START:
467 parse_array(lex, sem);
470 parse_scalar(lex, sem);
474 (*aend) (sem->semstate, isnull);
478 parse_array(JsonLexContext *lex, JsonSemAction *sem)
481 * an array is a possibly empty sequence of array elements, separated by
482 * commas and surrounded by square brackets.
484 json_struct_action astart = sem->array_start;
485 json_struct_action aend = sem->array_end;
488 (*astart) (sem->semstate);
491 * Data inside an array is at a higher nesting level than the array
492 * itself. Note that we increment this after we call the semantic routine
493 * for the array start and restore it before we call the routine for the
498 lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
499 if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
502 parse_array_element(lex, sem);
504 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
505 parse_array_element(lex, sem);
508 lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
513 (*aend) (sem->semstate);
517 * Lex one token from the input stream.
520 json_lex(JsonLexContext *lex)
525 /* Skip leading whitespace. */
526 s = lex->token_terminator;
527 len = s - lex->input;
528 while (len < lex->input_length &&
529 (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
536 lex->token_start = s;
538 /* Determine token type. */
539 if (len >= lex->input_length)
541 lex->token_start = NULL;
542 lex->prev_token_terminator = lex->token_terminator;
543 lex->token_terminator = s;
544 lex->token_type = JSON_TOKEN_END;
549 /* Single-character token, some kind of punctuation mark. */
551 lex->prev_token_terminator = lex->token_terminator;
552 lex->token_terminator = s + 1;
553 lex->token_type = JSON_TOKEN_OBJECT_START;
556 lex->prev_token_terminator = lex->token_terminator;
557 lex->token_terminator = s + 1;
558 lex->token_type = JSON_TOKEN_OBJECT_END;
561 lex->prev_token_terminator = lex->token_terminator;
562 lex->token_terminator = s + 1;
563 lex->token_type = JSON_TOKEN_ARRAY_START;
566 lex->prev_token_terminator = lex->token_terminator;
567 lex->token_terminator = s + 1;
568 lex->token_type = JSON_TOKEN_ARRAY_END;
571 lex->prev_token_terminator = lex->token_terminator;
572 lex->token_terminator = s + 1;
573 lex->token_type = JSON_TOKEN_COMMA;
576 lex->prev_token_terminator = lex->token_terminator;
577 lex->token_terminator = s + 1;
578 lex->token_type = JSON_TOKEN_COLON;
582 json_lex_string(lex);
583 lex->token_type = JSON_TOKEN_STRING;
586 /* Negative number. */
587 json_lex_number(lex, s + 1, NULL);
588 lex->token_type = JSON_TOKEN_NUMBER;
600 /* Positive number. */
601 json_lex_number(lex, s, NULL);
602 lex->token_type = JSON_TOKEN_NUMBER;
609 * We're not dealing with a string, number, legal
610 * punctuation mark, or end of string. The only legal
611 * tokens we might find here are true, false, and null,
612 * but for error reporting purposes we scan until we see a
613 * non-alphanumeric character. That way, we can report
614 * the whole word as an unexpected token, rather than just
615 * some unintuitive prefix thereof.
617 for (p = s; p - s < lex->input_length - len && JSON_ALPHANUMERIC_CHAR(*p); p++)
621 * We got some sort of unexpected punctuation or an
622 * otherwise unexpected character, so just complain about
623 * that one character.
627 lex->prev_token_terminator = lex->token_terminator;
628 lex->token_terminator = s + 1;
629 report_invalid_token(lex);
633 * We've got a real alphanumeric token here. If it
634 * happens to be true, false, or null, all is well. If
637 lex->prev_token_terminator = lex->token_terminator;
638 lex->token_terminator = p;
641 if (memcmp(s, "true", 4) == 0)
642 lex->token_type = JSON_TOKEN_TRUE;
643 else if (memcmp(s, "null", 4) == 0)
644 lex->token_type = JSON_TOKEN_NULL;
646 report_invalid_token(lex);
648 else if (p - s == 5 && memcmp(s, "false", 5) == 0)
649 lex->token_type = JSON_TOKEN_FALSE;
651 report_invalid_token(lex);
654 } /* end of switch */
658 * The next token in the input stream is known to be a string; lex it.
661 json_lex_string(JsonLexContext *lex)
665 int hi_surrogate = -1;
667 if (lex->strval != NULL)
668 resetStringInfo(lex->strval);
670 Assert(lex->input_length > 0);
671 s = lex->token_start;
672 len = lex->token_start - lex->input;
677 /* Premature end of the string. */
678 if (len >= lex->input_length)
680 lex->token_terminator = s;
681 report_invalid_token(lex);
685 else if ((unsigned char) *s < 32)
687 /* Per RFC4627, these characters MUST be escaped. */
688 /* Since *s isn't printable, exclude it from the context string */
689 lex->token_terminator = s;
691 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
692 errmsg("invalid input syntax for type json"),
693 errdetail("Character with value 0x%02x must be escaped.",
695 report_json_context(lex)));
699 /* OK, we have an escape character. */
702 if (len >= lex->input_length)
704 lex->token_terminator = s;
705 report_invalid_token(lex);
712 for (i = 1; i <= 4; i++)
716 if (len >= lex->input_length)
718 lex->token_terminator = s;
719 report_invalid_token(lex);
721 else if (*s >= '0' && *s <= '9')
722 ch = (ch * 16) + (*s - '0');
723 else if (*s >= 'a' && *s <= 'f')
724 ch = (ch * 16) + (*s - 'a') + 10;
725 else if (*s >= 'A' && *s <= 'F')
726 ch = (ch * 16) + (*s - 'A') + 10;
729 lex->token_terminator = s + pg_mblen(s);
731 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
732 errmsg("invalid input syntax for type json"),
733 errdetail("\"\\u\" must be followed by four hexadecimal digits."),
734 report_json_context(lex)));
737 if (lex->strval != NULL)
742 if (ch >= 0xd800 && ch <= 0xdbff)
744 if (hi_surrogate != -1)
746 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
747 errmsg("invalid input syntax for type json"),
748 errdetail("Unicode high surrogate must not follow a high surrogate."),
749 report_json_context(lex)));
750 hi_surrogate = (ch & 0x3ff) << 10;
753 else if (ch >= 0xdc00 && ch <= 0xdfff)
755 if (hi_surrogate == -1)
757 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
758 errmsg("invalid input syntax for type json"),
759 errdetail("Unicode low surrogate must follow a high surrogate."),
760 report_json_context(lex)));
761 ch = 0x10000 + hi_surrogate + (ch & 0x3ff);
765 if (hi_surrogate != -1)
767 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
768 errmsg("invalid input syntax for type json"),
769 errdetail("Unicode low surrogate must follow a high surrogate."),
770 report_json_context(lex)));
773 * For UTF8, replace the escape sequence by the actual
774 * utf8 character in lex->strval. Do this also for other
775 * encodings if the escape designates an ASCII character,
776 * otherwise raise an error. We don't ever unescape a
777 * \u0000, since that would result in an impermissible nul
783 appendStringInfoString(lex->strval, "\\u0000");
785 else if (GetDatabaseEncoding() == PG_UTF8)
787 unicode_to_utf8(ch, (unsigned char *) utf8str);
788 utf8len = pg_utf_mblen((unsigned char *) utf8str);
789 appendBinaryStringInfo(lex->strval, utf8str, utf8len);
791 else if (ch <= 0x007f)
794 * This is the only way to designate things like a
795 * form feed character in JSON, so it's useful in all
798 appendStringInfoChar(lex->strval, (char) ch);
803 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
804 errmsg("invalid input syntax for type json"),
805 errdetail("Unicode escape values cannot be used for code point values above 007F when the server encoding is not UTF8."),
806 report_json_context(lex)));
811 else if (lex->strval != NULL)
813 if (hi_surrogate != -1)
815 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
816 errmsg("invalid input syntax for type json"),
817 errdetail("Unicode low surrogate must follow a high surrogate."),
818 report_json_context(lex)));
825 appendStringInfoChar(lex->strval, *s);
828 appendStringInfoChar(lex->strval, '\b');
831 appendStringInfoChar(lex->strval, '\f');
834 appendStringInfoChar(lex->strval, '\n');
837 appendStringInfoChar(lex->strval, '\r');
840 appendStringInfoChar(lex->strval, '\t');
843 /* Not a valid string escape, so error out. */
844 lex->token_terminator = s + pg_mblen(s);
846 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
847 errmsg("invalid input syntax for type json"),
848 errdetail("Escape sequence \"\\%s\" is invalid.",
850 report_json_context(lex)));
853 else if (strchr("\"\\/bfnrt", *s) == NULL)
856 * Simpler processing if we're not bothered about de-escaping
858 * It's very tempting to remove the strchr() call here and
859 * replace it with a switch statement, but testing so far has
860 * shown it's not a performance win.
862 lex->token_terminator = s + pg_mblen(s);
864 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
865 errmsg("invalid input syntax for type json"),
866 errdetail("Escape sequence \"\\%s\" is invalid.",
868 report_json_context(lex)));
872 else if (lex->strval != NULL)
874 if (hi_surrogate != -1)
876 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
877 errmsg("invalid input syntax for type json"),
878 errdetail("Unicode low surrogate must follow a high surrogate."),
879 report_json_context(lex)));
881 appendStringInfoChar(lex->strval, *s);
886 if (hi_surrogate != -1)
888 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
889 errmsg("invalid input syntax for type json"),
890 errdetail("Unicode low surrogate must follow a high surrogate."),
891 report_json_context(lex)));
893 /* Hooray, we found the end of the string! */
894 lex->prev_token_terminator = lex->token_terminator;
895 lex->token_terminator = s + 1;
898 /*-------------------------------------------------------------------------
899 * The next token in the input stream is known to be a number; lex it.
901 * In JSON, a number consists of four parts:
903 * (1) An optional minus sign ('-').
905 * (2) Either a single '0', or a string of one or more digits that does not
908 * (3) An optional decimal part, consisting of a period ('.') followed by
909 * one or more digits. (Note: While this part can be omitted
910 * completely, it's not OK to have only the decimal point without
911 * any digits afterwards.)
913 * (4) An optional exponent part, consisting of 'e' or 'E', optionally
914 * followed by '+' or '-', followed by one or more digits. (Note:
915 * As with the decimal part, if 'e' or 'E' is present, it must be
916 * followed by at least one digit.)
918 * The 's' argument to this function points to the ostensible beginning
919 * of part 2 - i.e. the character after any optional minus sign, and the
920 * first character of the string if there is none.
922 *-------------------------------------------------------------------------
925 json_lex_number(JsonLexContext *lex, char *s, bool *num_err)
931 len = s - lex->input;
932 /* Part (1): leading sign indicator. */
933 /* Caller already did this for us; so do nothing. */
935 /* Part (2): parse main digit string. */
941 else if (*s >= '1' && *s <= '9')
947 } while (len < lex->input_length && *s >= '0' && *s <= '9');
952 /* Part (3): parse optional decimal portion. */
953 if (len < lex->input_length && *s == '.')
957 if (len == lex->input_length || *s < '0' || *s > '9')
965 } while (len < lex->input_length && *s >= '0' && *s <= '9');
969 /* Part (4): parse optional exponent. */
970 if (len < lex->input_length && (*s == 'e' || *s == 'E'))
974 if (len < lex->input_length && (*s == '+' || *s == '-'))
979 if (len == lex->input_length || *s < '0' || *s > '9')
987 } while (len < lex->input_length && *s >= '0' && *s <= '9');
992 * Check for trailing garbage. As in json_lex(), any alphanumeric stuff
993 * here should be considered part of the token for error-reporting
996 for (p = s; len < lex->input_length && JSON_ALPHANUMERIC_CHAR(*p); p++, len++)
1001 /* let the caller handle the error */
1006 lex->prev_token_terminator = lex->token_terminator;
1007 lex->token_terminator = p;
1009 report_invalid_token(lex);
1014 * Report a parse error.
1016 * lex->token_start and lex->token_terminator must identify the current token.
1019 report_parse_error(JsonParseContext ctx, JsonLexContext *lex)
1024 /* Handle case where the input ended prematurely. */
1025 if (lex->token_start == NULL || lex->token_type == JSON_TOKEN_END)
1027 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1028 errmsg("invalid input syntax for type json"),
1029 errdetail("The input string ended unexpectedly."),
1030 report_json_context(lex)));
1032 /* Separate out the current token. */
1033 toklen = lex->token_terminator - lex->token_start;
1034 token = palloc(toklen + 1);
1035 memcpy(token, lex->token_start, toklen);
1036 token[toklen] = '\0';
1038 /* Complain, with the appropriate detail message. */
1039 if (ctx == JSON_PARSE_END)
1041 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1042 errmsg("invalid input syntax for type json"),
1043 errdetail("Expected end of input, but found \"%s\".",
1045 report_json_context(lex)));
1050 case JSON_PARSE_VALUE:
1052 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1053 errmsg("invalid input syntax for type json"),
1054 errdetail("Expected JSON value, but found \"%s\".",
1056 report_json_context(lex)));
1058 case JSON_PARSE_STRING:
1060 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1061 errmsg("invalid input syntax for type json"),
1062 errdetail("Expected string, but found \"%s\".",
1064 report_json_context(lex)));
1066 case JSON_PARSE_ARRAY_START:
1068 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1069 errmsg("invalid input syntax for type json"),
1070 errdetail("Expected array element or \"]\", but found \"%s\".",
1072 report_json_context(lex)));
1074 case JSON_PARSE_ARRAY_NEXT:
1076 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1077 errmsg("invalid input syntax for type json"),
1078 errdetail("Expected \",\" or \"]\", but found \"%s\".",
1080 report_json_context(lex)));
1082 case JSON_PARSE_OBJECT_START:
1084 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1085 errmsg("invalid input syntax for type json"),
1086 errdetail("Expected string or \"}\", but found \"%s\".",
1088 report_json_context(lex)));
1090 case JSON_PARSE_OBJECT_LABEL:
1092 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1093 errmsg("invalid input syntax for type json"),
1094 errdetail("Expected \":\", but found \"%s\".",
1096 report_json_context(lex)));
1098 case JSON_PARSE_OBJECT_NEXT:
1100 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1101 errmsg("invalid input syntax for type json"),
1102 errdetail("Expected \",\" or \"}\", but found \"%s\".",
1104 report_json_context(lex)));
1106 case JSON_PARSE_OBJECT_COMMA:
1108 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1109 errmsg("invalid input syntax for type json"),
1110 errdetail("Expected string, but found \"%s\".",
1112 report_json_context(lex)));
1115 elog(ERROR, "unexpected json parse state: %d", ctx);
1121 * Report an invalid input token.
1123 * lex->token_start and lex->token_terminator must identify the token.
1126 report_invalid_token(JsonLexContext *lex)
1131 /* Separate out the offending token. */
1132 toklen = lex->token_terminator - lex->token_start;
1133 token = palloc(toklen + 1);
1134 memcpy(token, lex->token_start, toklen);
1135 token[toklen] = '\0';
1138 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1139 errmsg("invalid input syntax for type json"),
1140 errdetail("Token \"%s\" is invalid.", token),
1141 report_json_context(lex)));
1145 * Report a CONTEXT line for bogus JSON input.
1147 * lex->token_terminator must be set to identify the spot where we detected
1148 * the error. Note that lex->token_start might be NULL, in case we recognized
1151 * The return value isn't meaningful, but we make it non-void so that this
1152 * can be invoked inside ereport().
1155 report_json_context(JsonLexContext *lex)
1157 const char *context_start;
1158 const char *context_end;
1159 const char *line_start;
1166 /* Choose boundaries for the part of the input we will display */
1167 context_start = lex->input;
1168 context_end = lex->token_terminator;
1169 line_start = context_start;
1173 /* Always advance over newlines */
1174 if (context_start < context_end && *context_start == '\n')
1177 line_start = context_start;
1181 /* Otherwise, done as soon as we are close enough to context_end */
1182 if (context_end - context_start < 50)
1184 /* Advance to next multibyte character */
1185 if (IS_HIGHBIT_SET(*context_start))
1186 context_start += pg_mblen(context_start);
1192 * We add "..." to indicate that the excerpt doesn't start at the
1193 * beginning of the line ... but if we're within 3 characters of the
1194 * beginning of the line, we might as well just show the whole line.
1196 if (context_start - line_start <= 3)
1197 context_start = line_start;
1199 /* Get a null-terminated copy of the data to present */
1200 ctxtlen = context_end - context_start;
1201 ctxt = palloc(ctxtlen + 1);
1202 memcpy(ctxt, context_start, ctxtlen);
1203 ctxt[ctxtlen] = '\0';
1206 * Show the context, prefixing "..." if not starting at start of line, and
1207 * suffixing "..." if not ending at end of line.
1209 prefix = (context_start > line_start) ? "..." : "";
1210 suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : "";
1212 return errcontext("JSON data, line %d: %s%s%s",
1213 line_number, prefix, ctxt, suffix);
1217 * Extract a single, possibly multi-byte char from the input string.
1220 extract_mb_char(char *s)
1226 res = palloc(len + 1);
1227 memcpy(res, s, len);
1234 * Determine how we want to print values of a given type in datum_to_json.
1236 * Given the datatype OID, return its JsonTypeCategory, as well as the type's
1237 * output function OID. If the returned category is JSONTYPE_CAST, we
1238 * return the OID of the type->JSON cast function instead.
1241 json_categorize_type(Oid typoid,
1242 JsonTypeCategory *tcategory,
1247 /* Look through any domain */
1248 typoid = getBaseType(typoid);
1250 /* We'll usually need to return the type output function */
1251 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1253 /* Check for known types */
1257 *tcategory = JSONTYPE_BOOL;
1266 *tcategory = JSONTYPE_NUMERIC;
1270 *tcategory = JSONTYPE_TIMESTAMP;
1273 case TIMESTAMPTZOID:
1274 *tcategory = JSONTYPE_TIMESTAMPTZ;
1279 *tcategory = JSONTYPE_JSON;
1283 /* Check for arrays and composites */
1284 if (OidIsValid(get_element_type(typoid)))
1285 *tcategory = JSONTYPE_ARRAY;
1286 else if (type_is_rowtype(typoid))
1287 *tcategory = JSONTYPE_COMPOSITE;
1290 /* It's probably the general case ... */
1291 *tcategory = JSONTYPE_OTHER;
1292 /* but let's look for a cast to json, if it's not built-in */
1293 if (typoid >= FirstNormalObjectId)
1297 tuple = SearchSysCache2(CASTSOURCETARGET,
1298 ObjectIdGetDatum(typoid),
1299 ObjectIdGetDatum(JSONOID));
1300 if (HeapTupleIsValid(tuple))
1302 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1304 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1306 *tcategory = JSONTYPE_CAST;
1307 *outfuncoid = castForm->castfunc;
1310 ReleaseSysCache(tuple);
1319 * Turn a Datum into JSON text, appending the string to "result".
1321 * tcategory and outfuncoid are from a previous call to json_categorize_type,
1322 * except that if is_null is true then they can be invalid.
1324 * If key_scalar is true, the value is being printed as a key, so insist
1325 * it's of an acceptable type, and force it to be quoted.
1328 datum_to_json(Datum val, bool is_null, StringInfo result,
1329 JsonTypeCategory tcategory, Oid outfuncoid,
1335 JsonLexContext dummy_lex;
1339 appendStringInfoString(result, "null");
1344 (tcategory == JSONTYPE_ARRAY ||
1345 tcategory == JSONTYPE_COMPOSITE ||
1346 tcategory == JSONTYPE_JSON ||
1347 tcategory == JSONTYPE_CAST))
1349 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1350 errmsg("key value must be scalar, not array, composite, or json")));
1354 case JSONTYPE_ARRAY:
1355 array_to_json_internal(val, result, false);
1357 case JSONTYPE_COMPOSITE:
1358 composite_to_json(val, result, false);
1361 outputstr = DatumGetBool(val) ? "true" : "false";
1363 escape_json(result, outputstr);
1365 appendStringInfoString(result, outputstr);
1367 case JSONTYPE_NUMERIC:
1368 outputstr = OidOutputFunctionCall(outfuncoid, val);
1371 /* always quote keys */
1372 escape_json(result, outputstr);
1377 * Don't call escape_json for a non-key if it's a valid JSON
1380 dummy_lex.input = *outputstr == '-' ? outputstr + 1 : outputstr;
1381 dummy_lex.input_length = strlen(dummy_lex.input);
1382 json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error);
1384 appendStringInfoString(result, outputstr);
1386 escape_json(result, outputstr);
1390 case JSONTYPE_TIMESTAMP:
1392 Timestamp timestamp;
1395 char buf[MAXDATELEN + 1];
1397 timestamp = DatumGetTimestamp(val);
1399 /* XSD doesn't support infinite values */
1400 if (TIMESTAMP_NOT_FINITE(timestamp))
1402 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1403 errmsg("timestamp out of range"),
1404 errdetail("JSON does not support infinite timestamp values.")));
1405 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1406 EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
1409 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1410 errmsg("timestamp out of range")));
1412 appendStringInfo(result,"\"%s\"",buf);
1415 case JSONTYPE_TIMESTAMPTZ:
1417 TimestampTz timestamp;
1421 const char *tzn = NULL;
1422 char buf[MAXDATELEN + 1];
1424 timestamp = DatumGetTimestamp(val);
1426 /* XSD doesn't support infinite values */
1427 if (TIMESTAMP_NOT_FINITE(timestamp))
1429 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1430 errmsg("timestamp out of range"),
1431 errdetail("JSON does not support infinite timestamp values.")));
1432 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1433 EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
1436 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1437 errmsg("timestamp out of range")));
1439 appendStringInfo(result,"\"%s\"",buf);
1443 /* JSON and JSONB output will already be escaped */
1444 outputstr = OidOutputFunctionCall(outfuncoid, val);
1445 appendStringInfoString(result, outputstr);
1449 /* outfuncoid refers to a cast function, not an output function */
1450 jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val));
1451 outputstr = text_to_cstring(jsontext);
1452 appendStringInfoString(result, outputstr);
1457 outputstr = OidOutputFunctionCall(outfuncoid, val);
1458 if (key_scalar && *outputstr == '\0')
1460 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1461 errmsg("key value must not be empty")));
1462 escape_json(result, outputstr);
1469 * Process a single dimension of an array.
1470 * If it's the innermost dimension, output the values, otherwise call
1471 * ourselves recursively to process the next dimension.
1474 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1475 bool *nulls, int *valcount, JsonTypeCategory tcategory,
1476 Oid outfuncoid, bool use_line_feeds)
1481 Assert(dim < ndims);
1483 sep = use_line_feeds ? ",\n " : ",";
1485 appendStringInfoChar(result, '[');
1487 for (i = 1; i <= dims[dim]; i++)
1490 appendStringInfoString(result, sep);
1492 if (dim + 1 == ndims)
1494 datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1501 * Do we want line feeds on inner dimensions of arrays? For now
1504 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1505 valcount, tcategory, outfuncoid, false);
1509 appendStringInfoChar(result, ']');
1513 * Turn an array into JSON.
1516 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1518 ArrayType *v = DatumGetArrayTypeP(array);
1519 Oid element_type = ARR_ELEMTYPE(v);
1529 JsonTypeCategory tcategory;
1534 nitems = ArrayGetNItems(ndim, dim);
1538 appendStringInfoString(result, "[]");
1542 get_typlenbyvalalign(element_type,
1543 &typlen, &typbyval, &typalign);
1545 json_categorize_type(element_type,
1546 &tcategory, &outfuncoid);
1548 deconstruct_array(v, element_type, typlen, typbyval,
1549 typalign, &elements, &nulls,
1552 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1553 outfuncoid, use_line_feeds);
1560 * Turn a composite / record into JSON.
1563 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1569 HeapTupleData tmptup,
1572 bool needsep = false;
1575 sep = use_line_feeds ? ",\n " : ",";
1577 td = DatumGetHeapTupleHeader(composite);
1579 /* Extract rowtype info and find a tupdesc */
1580 tupType = HeapTupleHeaderGetTypeId(td);
1581 tupTypmod = HeapTupleHeaderGetTypMod(td);
1582 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1584 /* Build a temporary HeapTuple control structure */
1585 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1589 appendStringInfoChar(result, '{');
1591 for (i = 0; i < tupdesc->natts; i++)
1596 JsonTypeCategory tcategory;
1599 if (tupdesc->attrs[i]->attisdropped)
1603 appendStringInfoString(result, sep);
1606 attname = NameStr(tupdesc->attrs[i]->attname);
1607 escape_json(result, attname);
1608 appendStringInfoChar(result, ':');
1610 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1614 tcategory = JSONTYPE_NULL;
1615 outfuncoid = InvalidOid;
1618 json_categorize_type(tupdesc->attrs[i]->atttypid,
1619 &tcategory, &outfuncoid);
1621 datum_to_json(val, isnull, result, tcategory, outfuncoid, false);
1624 appendStringInfoChar(result, '}');
1625 ReleaseTupleDesc(tupdesc);
1629 * Append JSON text for "val" to "result".
1631 * This is just a thin wrapper around datum_to_json. If the same type will be
1632 * printed many times, avoid using this; better to do the json_categorize_type
1633 * lookups only once.
1636 add_json(Datum val, bool is_null, StringInfo result,
1637 Oid val_type, bool key_scalar)
1639 JsonTypeCategory tcategory;
1642 if (val_type == InvalidOid)
1644 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1645 errmsg("could not determine input data type")));
1649 tcategory = JSONTYPE_NULL;
1650 outfuncoid = InvalidOid;
1653 json_categorize_type(val_type,
1654 &tcategory, &outfuncoid);
1656 datum_to_json(val, is_null, result, tcategory, outfuncoid, key_scalar);
1660 * SQL function array_to_json(row)
1663 array_to_json(PG_FUNCTION_ARGS)
1665 Datum array = PG_GETARG_DATUM(0);
1668 result = makeStringInfo();
1670 array_to_json_internal(array, result, false);
1672 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1676 * SQL function array_to_json(row, prettybool)
1679 array_to_json_pretty(PG_FUNCTION_ARGS)
1681 Datum array = PG_GETARG_DATUM(0);
1682 bool use_line_feeds = PG_GETARG_BOOL(1);
1685 result = makeStringInfo();
1687 array_to_json_internal(array, result, use_line_feeds);
1689 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1693 * SQL function row_to_json(row)
1696 row_to_json(PG_FUNCTION_ARGS)
1698 Datum array = PG_GETARG_DATUM(0);
1701 result = makeStringInfo();
1703 composite_to_json(array, result, false);
1705 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1709 * SQL function row_to_json(row, prettybool)
1712 row_to_json_pretty(PG_FUNCTION_ARGS)
1714 Datum array = PG_GETARG_DATUM(0);
1715 bool use_line_feeds = PG_GETARG_BOOL(1);
1718 result = makeStringInfo();
1720 composite_to_json(array, result, use_line_feeds);
1722 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1726 * SQL function to_json(anyvalue)
1729 to_json(PG_FUNCTION_ARGS)
1731 Datum val = PG_GETARG_DATUM(0);
1732 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1734 JsonTypeCategory tcategory;
1737 if (val_type == InvalidOid)
1739 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1740 errmsg("could not determine input data type")));
1742 json_categorize_type(val_type,
1743 &tcategory, &outfuncoid);
1745 result = makeStringInfo();
1747 datum_to_json(val, false, result, tcategory, outfuncoid, false);
1749 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1753 * json_agg transition function
1756 json_agg_transfn(PG_FUNCTION_ARGS)
1758 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1759 MemoryContext aggcontext,
1763 JsonTypeCategory tcategory;
1766 if (val_type == InvalidOid)
1768 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1769 errmsg("could not determine input data type")));
1771 if (!AggCheckCallContext(fcinfo, &aggcontext))
1773 /* cannot be called directly because of internal-type argument */
1774 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1777 if (PG_ARGISNULL(0))
1780 * Make this StringInfo in a context where it will persist for the
1781 * duration of the aggregate call. MemoryContextSwitchTo is only
1782 * needed the first time, as the StringInfo routines make sure they
1783 * use the right context to enlarge the object if necessary.
1785 oldcontext = MemoryContextSwitchTo(aggcontext);
1786 state = makeStringInfo();
1787 MemoryContextSwitchTo(oldcontext);
1789 appendStringInfoChar(state, '[');
1793 state = (StringInfo) PG_GETARG_POINTER(0);
1794 appendStringInfoString(state, ", ");
1797 /* fast path for NULLs */
1798 if (PG_ARGISNULL(1))
1800 datum_to_json((Datum) 0, true, state, JSONTYPE_NULL, InvalidOid, false);
1801 PG_RETURN_POINTER(state);
1804 val = PG_GETARG_DATUM(1);
1806 /* XXX we do this every time?? */
1807 json_categorize_type(val_type,
1808 &tcategory, &outfuncoid);
1810 /* add some whitespace if structured type and not first item */
1811 if (!PG_ARGISNULL(0) &&
1812 (tcategory == JSONTYPE_ARRAY || tcategory == JSONTYPE_COMPOSITE))
1814 appendStringInfoString(state, "\n ");
1817 datum_to_json(val, false, state, tcategory, outfuncoid, false);
1820 * The transition type for array_agg() is declared to be "internal", which
1821 * is a pass-by-value type the same size as a pointer. So we can safely
1822 * pass the ArrayBuildState pointer through nodeAgg.c's machinations.
1824 PG_RETURN_POINTER(state);
1828 * json_agg final function
1831 json_agg_finalfn(PG_FUNCTION_ARGS)
1835 /* cannot be called directly because of internal-type argument */
1836 Assert(AggCheckCallContext(fcinfo, NULL));
1838 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1843 appendStringInfoChar(state, ']');
1845 PG_RETURN_TEXT_P(cstring_to_text_with_len(state->data, state->len));
1849 * json_object_agg transition function.
1851 * aggregate two input columns as a single json value.
1854 json_object_agg_transfn(PG_FUNCTION_ARGS)
1857 MemoryContext aggcontext,
1862 if (!AggCheckCallContext(fcinfo, &aggcontext))
1864 /* cannot be called directly because of internal-type argument */
1865 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1868 if (PG_ARGISNULL(0))
1871 * Make this StringInfo in a context where it will persist for the
1872 * duration off the aggregate call. It's only needed for this initial
1873 * piece, as the StringInfo routines make sure they use the right
1874 * context to enlarge the object if necessary.
1876 oldcontext = MemoryContextSwitchTo(aggcontext);
1877 state = makeStringInfo();
1878 MemoryContextSwitchTo(oldcontext);
1880 appendStringInfoString(state, "{ ");
1884 state = (StringInfo) PG_GETARG_POINTER(0);
1885 appendStringInfoString(state, ", ");
1888 if (PG_ARGISNULL(1))
1890 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1891 errmsg("field name must not be null")));
1894 val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1897 * turn a constant (more or less literal) value that's of unknown type
1898 * into text. Unknowns come in as a cstring pointer.
1900 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, 1))
1903 arg = CStringGetTextDatum(PG_GETARG_POINTER(1));
1907 arg = PG_GETARG_DATUM(1);
1910 if (val_type == InvalidOid || val_type == UNKNOWNOID)
1912 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1913 errmsg("could not determine data type for argument %d", 1)));
1915 add_json(arg, false, state, val_type, true);
1917 appendStringInfoString(state, " : ");
1919 val_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
1920 /* see comments above */
1921 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, 2))
1924 if (PG_ARGISNULL(2))
1927 arg = CStringGetTextDatum(PG_GETARG_POINTER(2));
1931 arg = PG_GETARG_DATUM(2);
1934 if (val_type == InvalidOid || val_type == UNKNOWNOID)
1936 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1937 errmsg("could not determine data type for argument %d", 2)));
1939 add_json(arg, PG_ARGISNULL(2), state, val_type, false);
1941 PG_RETURN_POINTER(state);
1945 * json_object_agg final function.
1949 json_object_agg_finalfn(PG_FUNCTION_ARGS)
1953 /* cannot be called directly because of internal-type argument */
1954 Assert(AggCheckCallContext(fcinfo, NULL));
1956 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1959 PG_RETURN_TEXT_P(cstring_to_text("{}"));
1961 appendStringInfoString(state, " }");
1963 PG_RETURN_TEXT_P(cstring_to_text_with_len(state->data, state->len));
1967 * SQL function json_build_object(variadic "any")
1970 json_build_object(PG_FUNCTION_ARGS)
1972 int nargs = PG_NARGS();
1982 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1983 errmsg("invalid number or arguments"),
1984 errhint("Object must be matched key value pairs.")));
1986 result = makeStringInfo();
1988 appendStringInfoChar(result, '{');
1990 for (i = 0; i < nargs; i += 2)
1995 if (PG_ARGISNULL(i))
1997 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1998 errmsg("argument %d cannot be null", i + 1),
1999 errhint("Object keys should be text.")));
2000 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2003 * turn a constant (more or less literal) value that's of unknown type
2004 * into text. Unknowns come in as a cstring pointer.
2006 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i))
2009 if (PG_ARGISNULL(i))
2012 arg = CStringGetTextDatum(PG_GETARG_POINTER(i));
2016 arg = PG_GETARG_DATUM(i);
2018 if (val_type == InvalidOid || val_type == UNKNOWNOID)
2020 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2021 errmsg("could not determine data type for argument %d",
2023 appendStringInfoString(result, sep);
2025 add_json(arg, false, result, val_type, true);
2027 appendStringInfoString(result, " : ");
2031 val_type = get_fn_expr_argtype(fcinfo->flinfo, i + 1);
2032 /* see comments above */
2033 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i + 1))
2036 if (PG_ARGISNULL(i + 1))
2039 arg = CStringGetTextDatum(PG_GETARG_POINTER(i + 1));
2043 arg = PG_GETARG_DATUM(i + 1);
2045 if (val_type == InvalidOid || val_type == UNKNOWNOID)
2047 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2048 errmsg("could not determine data type for argument %d",
2050 add_json(arg, PG_ARGISNULL(i + 1), result, val_type, false);
2053 appendStringInfoChar(result, '}');
2055 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2060 * degenerate case of json_build_object where it gets 0 arguments.
2063 json_build_object_noargs(PG_FUNCTION_ARGS)
2065 PG_RETURN_TEXT_P(cstring_to_text_with_len("{}", 2));
2069 * SQL function json_build_array(variadic "any")
2072 json_build_array(PG_FUNCTION_ARGS)
2074 int nargs = PG_NARGS();
2082 result = makeStringInfo();
2084 appendStringInfoChar(result, '[');
2086 for (i = 0; i < nargs; i++)
2088 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2089 arg = PG_GETARG_DATUM(i + 1);
2090 /* see comments in json_build_object above */
2091 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i))
2094 if (PG_ARGISNULL(i))
2097 arg = CStringGetTextDatum(PG_GETARG_POINTER(i));
2101 arg = PG_GETARG_DATUM(i);
2103 if (val_type == InvalidOid || val_type == UNKNOWNOID)
2105 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2106 errmsg("could not determine data type for argument %d",
2108 appendStringInfoString(result, sep);
2110 add_json(arg, PG_ARGISNULL(i), result, val_type, false);
2112 appendStringInfoChar(result, ']');
2114 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2119 * degenerate case of json_build_array where it gets 0 arguments.
2122 json_build_array_noargs(PG_FUNCTION_ARGS)
2124 PG_RETURN_TEXT_P(cstring_to_text_with_len("[]", 2));
2128 * SQL function json_object(text[])
2130 * take a one or two dimensional array of text as name vale pairs
2131 * for a json object.
2135 json_object(PG_FUNCTION_ARGS)
2137 ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
2138 int ndims = ARR_NDIM(in_array);
2139 StringInfoData result;
2151 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2155 if ((ARR_DIMS(in_array)[0]) % 2)
2157 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2158 errmsg("array must have even number of elements")));
2162 if ((ARR_DIMS(in_array)[1]) != 2)
2164 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2165 errmsg("array must have two columns")));
2170 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2171 errmsg("wrong number of array subscripts")));
2174 deconstruct_array(in_array,
2175 TEXTOID, -1, false, 'i',
2176 &in_datums, &in_nulls, &in_count);
2178 count = in_count / 2;
2180 initStringInfo(&result);
2182 appendStringInfoChar(&result, '{');
2184 for (i = 0; i < count; ++i)
2186 if (in_nulls[i * 2])
2188 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2189 errmsg("null value not allowed for object key")));
2191 v = TextDatumGetCString(in_datums[i * 2]);
2193 appendStringInfoString(&result, ", ");
2194 escape_json(&result, v);
2195 appendStringInfoString(&result, " : ");
2197 if (in_nulls[i * 2 + 1])
2198 appendStringInfoString(&result, "null");
2201 v = TextDatumGetCString(in_datums[i * 2 + 1]);
2202 escape_json(&result, v);
2207 appendStringInfoChar(&result, '}');
2212 rval = cstring_to_text_with_len(result.data, result.len);
2215 PG_RETURN_TEXT_P(rval);
2220 * SQL function json_object(text[], text[])
2222 * take separate name and value arrays of text to construct a json object
2226 json_object_two_arg(PG_FUNCTION_ARGS)
2228 ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
2229 ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
2230 int nkdims = ARR_NDIM(key_array);
2231 int nvdims = ARR_NDIM(val_array);
2232 StringInfoData result;
2243 if (nkdims > 1 || nkdims != nvdims)
2245 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2246 errmsg("wrong number of array subscripts")));
2249 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2251 deconstruct_array(key_array,
2252 TEXTOID, -1, false, 'i',
2253 &key_datums, &key_nulls, &key_count);
2255 deconstruct_array(val_array,
2256 TEXTOID, -1, false, 'i',
2257 &val_datums, &val_nulls, &val_count);
2259 if (key_count != val_count)
2261 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2262 errmsg("mismatched array dimensions")));
2264 initStringInfo(&result);
2266 appendStringInfoChar(&result, '{');
2268 for (i = 0; i < key_count; ++i)
2272 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2273 errmsg("null value not allowed for object key")));
2275 v = TextDatumGetCString(key_datums[i]);
2277 appendStringInfoString(&result, ", ");
2278 escape_json(&result, v);
2279 appendStringInfoString(&result, " : ");
2282 appendStringInfoString(&result, "null");
2285 v = TextDatumGetCString(val_datums[i]);
2286 escape_json(&result, v);
2291 appendStringInfoChar(&result, '}');
2298 rval = cstring_to_text_with_len(result.data, result.len);
2301 PG_RETURN_TEXT_P(rval);
2307 * Produce a JSON string literal, properly escaping characters in the text.
2310 escape_json(StringInfo buf, const char *str)
2314 appendStringInfoCharMacro(buf, '\"');
2315 for (p = str; *p; p++)
2320 appendStringInfoString(buf, "\\b");
2323 appendStringInfoString(buf, "\\f");
2326 appendStringInfoString(buf, "\\n");
2329 appendStringInfoString(buf, "\\r");
2332 appendStringInfoString(buf, "\\t");
2335 appendStringInfoString(buf, "\\\"");
2339 * Unicode escapes are passed through as is. There is no
2340 * requirement that they denote a valid character in the
2341 * server encoding - indeed that is a big part of their
2344 * All we require is that they consist of \uXXXX where
2345 * the Xs are hexadecimal digits. It is the responsibility
2346 * of the caller of, say, to_json() to make sure that the
2347 * unicode escape is valid.
2349 * In the case of a jsonb string value being escaped, the
2350 * only unicode escape that should be present is \u0000,
2351 * all the other unicode escapes will have been resolved.
2354 isxdigit((unsigned char) p[2]) &&
2355 isxdigit((unsigned char) p[3]) &&
2356 isxdigit((unsigned char) p[4]) &&
2357 isxdigit((unsigned char) p[5]))
2358 appendStringInfoCharMacro(buf, *p);
2360 appendStringInfoString(buf, "\\\\");
2363 if ((unsigned char) *p < ' ')
2364 appendStringInfo(buf, "\\u%04x", (int) *p);
2366 appendStringInfoCharMacro(buf, *p);
2370 appendStringInfoCharMacro(buf, '\"');
2374 * SQL function json_typeof(json) -> text
2376 * Returns the type of the outermost JSON value as TEXT. Possible types are
2377 * "object", "array", "string", "number", "boolean", and "null".
2379 * Performs a single call to json_lex() to get the first token of the supplied
2380 * value. This initial token uniquely determines the value's type. As our
2381 * input must already have been validated by json_in() or json_recv(), the
2382 * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
2383 * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
2386 json_typeof(PG_FUNCTION_ARGS)
2390 JsonLexContext *lex;
2394 json = PG_GETARG_TEXT_P(0);
2395 lex = makeJsonLexContext(json, false);
2397 /* Lex exactly one token from the input and check its type. */
2399 tok = lex_peek(lex);
2402 case JSON_TOKEN_OBJECT_START:
2405 case JSON_TOKEN_ARRAY_START:
2408 case JSON_TOKEN_STRING:
2411 case JSON_TOKEN_NUMBER:
2414 case JSON_TOKEN_TRUE:
2415 case JSON_TOKEN_FALSE:
2418 case JSON_TOKEN_NULL:
2422 elog(ERROR, "unexpected json token: %d", tok);
2425 PG_RETURN_TEXT_P(cstring_to_text(type));