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/date.h"
29 #include "utils/datetime.h"
30 #include "utils/lsyscache.h"
31 #include "utils/json.h"
32 #include "utils/jsonapi.h"
33 #include "utils/typcache.h"
34 #include "utils/syscache.h"
37 * The context of the parser is maintained by the recursive descent
38 * mechanism, but is passed explicitly to the error reporting routine
39 * for better diagnostics.
41 typedef enum /* contexts of JSON parser */
43 JSON_PARSE_VALUE, /* expecting a value */
44 JSON_PARSE_STRING, /* expecting a string (for a field name) */
45 JSON_PARSE_ARRAY_START, /* saw '[', expecting value or ']' */
46 JSON_PARSE_ARRAY_NEXT, /* saw array element, expecting ',' or ']' */
47 JSON_PARSE_OBJECT_START, /* saw '{', expecting label or '}' */
48 JSON_PARSE_OBJECT_LABEL, /* saw object label, expecting ':' */
49 JSON_PARSE_OBJECT_NEXT, /* saw object value, expecting ',' or '}' */
50 JSON_PARSE_OBJECT_COMMA, /* saw object ',', expecting next label */
51 JSON_PARSE_END /* saw the end of a document, expect nothing */
54 typedef enum /* type categories for datum_to_json */
56 JSONTYPE_NULL, /* null, so we didn't bother to identify */
57 JSONTYPE_BOOL, /* boolean (built-in types only) */
58 JSONTYPE_NUMERIC, /* numeric (ditto) */
59 JSONTYPE_DATE, /* we use special formatting for datetimes */
62 JSONTYPE_JSON, /* JSON itself (and JSONB) */
63 JSONTYPE_ARRAY, /* array */
64 JSONTYPE_COMPOSITE, /* composite */
65 JSONTYPE_CAST, /* something with an explicit cast to JSON */
66 JSONTYPE_OTHER /* all else */
69 static inline void json_lex(JsonLexContext *lex);
70 static inline void json_lex_string(JsonLexContext *lex);
71 static inline void json_lex_number(JsonLexContext *lex, char *s, bool *num_err);
72 static inline void parse_scalar(JsonLexContext *lex, JsonSemAction *sem);
73 static void parse_object_field(JsonLexContext *lex, JsonSemAction *sem);
74 static void parse_object(JsonLexContext *lex, JsonSemAction *sem);
75 static void parse_array_element(JsonLexContext *lex, JsonSemAction *sem);
76 static void parse_array(JsonLexContext *lex, JsonSemAction *sem);
77 static void report_parse_error(JsonParseContext ctx, JsonLexContext *lex);
78 static void report_invalid_token(JsonLexContext *lex);
79 static int report_json_context(JsonLexContext *lex);
80 static char *extract_mb_char(char *s);
81 static void composite_to_json(Datum composite, StringInfo result,
83 static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
84 Datum *vals, bool *nulls, int *valcount,
85 JsonTypeCategory tcategory, Oid outfuncoid,
87 static void array_to_json_internal(Datum array, StringInfo result,
89 static void json_categorize_type(Oid typoid,
90 JsonTypeCategory *tcategory,
92 static void datum_to_json(Datum val, bool is_null, StringInfo result,
93 JsonTypeCategory tcategory, Oid outfuncoid,
95 static void add_json(Datum val, bool is_null, StringInfo result,
96 Oid val_type, bool key_scalar);
97 static text *catenate_stringinfo_string(StringInfo buffer, const char *addon);
99 /* the null action object used for pure validation */
100 static JsonSemAction nullSemAction =
102 NULL, NULL, NULL, NULL, NULL,
103 NULL, NULL, NULL, NULL, NULL
106 /* Recursive Descent parser support routines */
111 * what is the current look_ahead token?
113 static inline JsonTokenType
114 lex_peek(JsonLexContext *lex)
116 return lex->token_type;
122 * accept the look_ahead token and move the lexer to the next token if the
123 * look_ahead token matches the token parameter. In that case, and if required,
124 * also hand back the de-escaped lexeme.
126 * returns true if the token matched, false otherwise.
129 lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
131 if (lex->token_type == token)
135 if (lex->token_type == JSON_TOKEN_STRING)
137 if (lex->strval != NULL)
138 *lexeme = pstrdup(lex->strval->data);
142 int len = (lex->token_terminator - lex->token_start);
143 char *tokstr = palloc(len + 1);
145 memcpy(tokstr, lex->token_start, len);
159 * move the lexer to the next token if the current look_ahead token matches
160 * the parameter token. Otherwise, report an error.
163 lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
165 if (!lex_accept(lex, token, NULL))
166 report_parse_error(ctx, lex);;
169 /* chars to consider as part of an alphanumeric token */
170 #define JSON_ALPHANUMERIC_CHAR(c) \
171 (((c) >= 'a' && (c) <= 'z') || \
172 ((c) >= 'A' && (c) <= 'Z') || \
173 ((c) >= '0' && (c) <= '9') || \
177 /* utility function to check if a string is a valid JSON number */
179 IsValidJsonNumber(const char *str, int len)
182 JsonLexContext dummy_lex;
186 * json_lex_number expects a leading '-' to have been eaten already.
188 * having to cast away the constness of str is ugly, but there's not much
193 dummy_lex.input = (char *) str + 1;
194 dummy_lex.input_length = len - 1;
198 dummy_lex.input = (char *) str;
199 dummy_lex.input_length = len;
202 json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error);
204 return !numeric_error;
211 json_in(PG_FUNCTION_ARGS)
213 char *json = PG_GETARG_CSTRING(0);
214 text *result = cstring_to_text(json);
218 lex = makeJsonLexContext(result, false);
219 pg_parse_json(lex, &nullSemAction);
221 /* Internal representation is the same as text, for now */
222 PG_RETURN_TEXT_P(result);
229 json_out(PG_FUNCTION_ARGS)
231 /* we needn't detoast because text_to_cstring will handle that */
232 Datum txt = PG_GETARG_DATUM(0);
234 PG_RETURN_CSTRING(TextDatumGetCString(txt));
241 json_send(PG_FUNCTION_ARGS)
243 text *t = PG_GETARG_TEXT_PP(0);
246 pq_begintypsend(&buf);
247 pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
248 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
255 json_recv(PG_FUNCTION_ARGS)
257 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
262 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
265 lex = makeJsonLexContextCstringLen(str, nbytes, false);
266 pg_parse_json(lex, &nullSemAction);
268 PG_RETURN_TEXT_P(cstring_to_text_with_len(str, nbytes));
274 * lex constructor, with or without StringInfo object
275 * for de-escaped lexemes.
277 * Without is better as it makes the processing faster, so only make one
278 * if really required.
280 * If you already have the json as a text* value, use the first of these
281 * functions, otherwise use makeJsonLexContextCstringLen().
284 makeJsonLexContext(text *json, bool need_escapes)
286 return makeJsonLexContextCstringLen(VARDATA(json),
287 VARSIZE(json) - VARHDRSZ,
292 makeJsonLexContextCstringLen(char *json, int len, bool need_escapes)
294 JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
296 lex->input = lex->token_terminator = lex->line_start = json;
297 lex->line_number = 1;
298 lex->input_length = len;
300 lex->strval = makeStringInfo();
307 * Publicly visible entry point for the JSON parser.
309 * lex is a lexing context, set up for the json to be processed by calling
310 * makeJsonLexContext(). sem is a strucure of function pointers to semantic
311 * action routines to be called at appropriate spots during parsing, and a
312 * pointer to a state object to be passed to those routines.
315 pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
319 /* get the initial token */
324 /* parse by recursive descent */
327 case JSON_TOKEN_OBJECT_START:
328 parse_object(lex, sem);
330 case JSON_TOKEN_ARRAY_START:
331 parse_array(lex, sem);
334 parse_scalar(lex, sem); /* json can be a bare scalar */
337 lex_expect(JSON_PARSE_END, lex, JSON_TOKEN_END);
342 * Recursive Descent parse routines. There is one for each structural
343 * element in a json document:
344 * - scalar (string, number, true, false, null)
351 parse_scalar(JsonLexContext *lex, JsonSemAction *sem)
354 json_scalar_action sfunc = sem->scalar;
356 JsonTokenType tok = lex_peek(lex);
358 valaddr = sfunc == NULL ? NULL : &val;
360 /* a scalar must be a string, a number, true, false, or null */
363 case JSON_TOKEN_TRUE:
364 lex_accept(lex, JSON_TOKEN_TRUE, valaddr);
366 case JSON_TOKEN_FALSE:
367 lex_accept(lex, JSON_TOKEN_FALSE, valaddr);
369 case JSON_TOKEN_NULL:
370 lex_accept(lex, JSON_TOKEN_NULL, valaddr);
372 case JSON_TOKEN_NUMBER:
373 lex_accept(lex, JSON_TOKEN_NUMBER, valaddr);
375 case JSON_TOKEN_STRING:
376 lex_accept(lex, JSON_TOKEN_STRING, valaddr);
379 report_parse_error(JSON_PARSE_VALUE, lex);
383 (*sfunc) (sem->semstate, val, tok);
387 parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
390 * An object field is "fieldname" : value where value can be a scalar,
391 * object or array. Note: in user-facing docs and error messages, we
392 * generally call a field name a "key".
395 char *fname = NULL; /* keep compiler quiet */
396 json_ofield_action ostart = sem->object_field_start;
397 json_ofield_action oend = sem->object_field_end;
399 char **fnameaddr = NULL;
402 if (ostart != NULL || oend != NULL)
405 if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
406 report_parse_error(JSON_PARSE_STRING, lex);
408 lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
411 isnull = tok == JSON_TOKEN_NULL;
414 (*ostart) (sem->semstate, fname, isnull);
418 case JSON_TOKEN_OBJECT_START:
419 parse_object(lex, sem);
421 case JSON_TOKEN_ARRAY_START:
422 parse_array(lex, sem);
425 parse_scalar(lex, sem);
429 (*oend) (sem->semstate, fname, isnull);
433 parse_object(JsonLexContext *lex, JsonSemAction *sem)
436 * an object is a possibly empty sequence of object fields, separated by
437 * commas and surrounded by curly braces.
439 json_struct_action ostart = sem->object_start;
440 json_struct_action oend = sem->object_end;
444 (*ostart) (sem->semstate);
447 * Data inside an object is at a higher nesting level than the object
448 * itself. Note that we increment this after we call the semantic routine
449 * for the object start and restore it before we call the routine for the
454 /* we know this will succeeed, just clearing the token */
455 lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
460 case JSON_TOKEN_STRING:
461 parse_object_field(lex, sem);
462 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
463 parse_object_field(lex, sem);
465 case JSON_TOKEN_OBJECT_END:
468 /* case of an invalid initial token inside the object */
469 report_parse_error(JSON_PARSE_OBJECT_START, lex);
472 lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
477 (*oend) (sem->semstate);
481 parse_array_element(JsonLexContext *lex, JsonSemAction *sem)
483 json_aelem_action astart = sem->array_element_start;
484 json_aelem_action aend = sem->array_element_end;
485 JsonTokenType tok = lex_peek(lex);
489 isnull = tok == JSON_TOKEN_NULL;
492 (*astart) (sem->semstate, isnull);
494 /* an array element is any object, array or scalar */
497 case JSON_TOKEN_OBJECT_START:
498 parse_object(lex, sem);
500 case JSON_TOKEN_ARRAY_START:
501 parse_array(lex, sem);
504 parse_scalar(lex, sem);
508 (*aend) (sem->semstate, isnull);
512 parse_array(JsonLexContext *lex, JsonSemAction *sem)
515 * an array is a possibly empty sequence of array elements, separated by
516 * commas and surrounded by square brackets.
518 json_struct_action astart = sem->array_start;
519 json_struct_action aend = sem->array_end;
522 (*astart) (sem->semstate);
525 * Data inside an array is at a higher nesting level than the array
526 * itself. Note that we increment this after we call the semantic routine
527 * for the array start and restore it before we call the routine for the
532 lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
533 if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
536 parse_array_element(lex, sem);
538 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
539 parse_array_element(lex, sem);
542 lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
547 (*aend) (sem->semstate);
551 * Lex one token from the input stream.
554 json_lex(JsonLexContext *lex)
559 /* Skip leading whitespace. */
560 s = lex->token_terminator;
561 len = s - lex->input;
562 while (len < lex->input_length &&
563 (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
570 lex->token_start = s;
572 /* Determine token type. */
573 if (len >= lex->input_length)
575 lex->token_start = NULL;
576 lex->prev_token_terminator = lex->token_terminator;
577 lex->token_terminator = s;
578 lex->token_type = JSON_TOKEN_END;
583 /* Single-character token, some kind of punctuation mark. */
585 lex->prev_token_terminator = lex->token_terminator;
586 lex->token_terminator = s + 1;
587 lex->token_type = JSON_TOKEN_OBJECT_START;
590 lex->prev_token_terminator = lex->token_terminator;
591 lex->token_terminator = s + 1;
592 lex->token_type = JSON_TOKEN_OBJECT_END;
595 lex->prev_token_terminator = lex->token_terminator;
596 lex->token_terminator = s + 1;
597 lex->token_type = JSON_TOKEN_ARRAY_START;
600 lex->prev_token_terminator = lex->token_terminator;
601 lex->token_terminator = s + 1;
602 lex->token_type = JSON_TOKEN_ARRAY_END;
605 lex->prev_token_terminator = lex->token_terminator;
606 lex->token_terminator = s + 1;
607 lex->token_type = JSON_TOKEN_COMMA;
610 lex->prev_token_terminator = lex->token_terminator;
611 lex->token_terminator = s + 1;
612 lex->token_type = JSON_TOKEN_COLON;
616 json_lex_string(lex);
617 lex->token_type = JSON_TOKEN_STRING;
620 /* Negative number. */
621 json_lex_number(lex, s + 1, NULL);
622 lex->token_type = JSON_TOKEN_NUMBER;
634 /* Positive number. */
635 json_lex_number(lex, s, NULL);
636 lex->token_type = JSON_TOKEN_NUMBER;
643 * We're not dealing with a string, number, legal
644 * punctuation mark, or end of string. The only legal
645 * tokens we might find here are true, false, and null,
646 * but for error reporting purposes we scan until we see a
647 * non-alphanumeric character. That way, we can report
648 * the whole word as an unexpected token, rather than just
649 * some unintuitive prefix thereof.
651 for (p = s; p - s < lex->input_length - len && JSON_ALPHANUMERIC_CHAR(*p); p++)
655 * We got some sort of unexpected punctuation or an
656 * otherwise unexpected character, so just complain about
657 * that one character.
661 lex->prev_token_terminator = lex->token_terminator;
662 lex->token_terminator = s + 1;
663 report_invalid_token(lex);
667 * We've got a real alphanumeric token here. If it
668 * happens to be true, false, or null, all is well. If
671 lex->prev_token_terminator = lex->token_terminator;
672 lex->token_terminator = p;
675 if (memcmp(s, "true", 4) == 0)
676 lex->token_type = JSON_TOKEN_TRUE;
677 else if (memcmp(s, "null", 4) == 0)
678 lex->token_type = JSON_TOKEN_NULL;
680 report_invalid_token(lex);
682 else if (p - s == 5 && memcmp(s, "false", 5) == 0)
683 lex->token_type = JSON_TOKEN_FALSE;
685 report_invalid_token(lex);
688 } /* end of switch */
692 * The next token in the input stream is known to be a string; lex it.
695 json_lex_string(JsonLexContext *lex)
699 int hi_surrogate = -1;
701 if (lex->strval != NULL)
702 resetStringInfo(lex->strval);
704 Assert(lex->input_length > 0);
705 s = lex->token_start;
706 len = lex->token_start - lex->input;
711 /* Premature end of the string. */
712 if (len >= lex->input_length)
714 lex->token_terminator = s;
715 report_invalid_token(lex);
719 else if ((unsigned char) *s < 32)
721 /* Per RFC4627, these characters MUST be escaped. */
722 /* Since *s isn't printable, exclude it from the context string */
723 lex->token_terminator = s;
725 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
726 errmsg("invalid input syntax for type json"),
727 errdetail("Character with value 0x%02x must be escaped.",
729 report_json_context(lex)));
733 /* OK, we have an escape character. */
736 if (len >= lex->input_length)
738 lex->token_terminator = s;
739 report_invalid_token(lex);
746 for (i = 1; i <= 4; i++)
750 if (len >= lex->input_length)
752 lex->token_terminator = s;
753 report_invalid_token(lex);
755 else if (*s >= '0' && *s <= '9')
756 ch = (ch * 16) + (*s - '0');
757 else if (*s >= 'a' && *s <= 'f')
758 ch = (ch * 16) + (*s - 'a') + 10;
759 else if (*s >= 'A' && *s <= 'F')
760 ch = (ch * 16) + (*s - 'A') + 10;
763 lex->token_terminator = s + pg_mblen(s);
765 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
766 errmsg("invalid input syntax for type json"),
767 errdetail("\"\\u\" must be followed by four hexadecimal digits."),
768 report_json_context(lex)));
771 if (lex->strval != NULL)
776 if (ch >= 0xd800 && ch <= 0xdbff)
778 if (hi_surrogate != -1)
780 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
781 errmsg("invalid input syntax for type json"),
782 errdetail("Unicode high surrogate must not follow a high surrogate."),
783 report_json_context(lex)));
784 hi_surrogate = (ch & 0x3ff) << 10;
787 else if (ch >= 0xdc00 && ch <= 0xdfff)
789 if (hi_surrogate == -1)
791 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
792 errmsg("invalid input syntax for type json"),
793 errdetail("Unicode low surrogate must follow a high surrogate."),
794 report_json_context(lex)));
795 ch = 0x10000 + hi_surrogate + (ch & 0x3ff);
799 if (hi_surrogate != -1)
801 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
802 errmsg("invalid input syntax for type json"),
803 errdetail("Unicode low surrogate must follow a high surrogate."),
804 report_json_context(lex)));
807 * For UTF8, replace the escape sequence by the actual
808 * utf8 character in lex->strval. Do this also for other
809 * encodings if the escape designates an ASCII character,
810 * otherwise raise an error. We don't ever unescape a
811 * \u0000, since that would result in an impermissible nul
817 appendStringInfoString(lex->strval, "\\u0000");
819 else if (GetDatabaseEncoding() == PG_UTF8)
821 unicode_to_utf8(ch, (unsigned char *) utf8str);
822 utf8len = pg_utf_mblen((unsigned char *) utf8str);
823 appendBinaryStringInfo(lex->strval, utf8str, utf8len);
825 else if (ch <= 0x007f)
828 * This is the only way to designate things like a
829 * form feed character in JSON, so it's useful in all
832 appendStringInfoChar(lex->strval, (char) ch);
837 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
838 errmsg("invalid input syntax for type json"),
839 errdetail("Unicode escape values cannot be used for code point values above 007F when the server encoding is not UTF8."),
840 report_json_context(lex)));
845 else if (lex->strval != NULL)
847 if (hi_surrogate != -1)
849 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
850 errmsg("invalid input syntax for type json"),
851 errdetail("Unicode low surrogate must follow a high surrogate."),
852 report_json_context(lex)));
859 appendStringInfoChar(lex->strval, *s);
862 appendStringInfoChar(lex->strval, '\b');
865 appendStringInfoChar(lex->strval, '\f');
868 appendStringInfoChar(lex->strval, '\n');
871 appendStringInfoChar(lex->strval, '\r');
874 appendStringInfoChar(lex->strval, '\t');
877 /* Not a valid string escape, so error out. */
878 lex->token_terminator = s + pg_mblen(s);
880 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
881 errmsg("invalid input syntax for type json"),
882 errdetail("Escape sequence \"\\%s\" is invalid.",
884 report_json_context(lex)));
887 else if (strchr("\"\\/bfnrt", *s) == NULL)
890 * Simpler processing if we're not bothered about de-escaping
892 * It's very tempting to remove the strchr() call here and
893 * replace it with a switch statement, but testing so far has
894 * shown it's not a performance win.
896 lex->token_terminator = s + pg_mblen(s);
898 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
899 errmsg("invalid input syntax for type json"),
900 errdetail("Escape sequence \"\\%s\" is invalid.",
902 report_json_context(lex)));
906 else if (lex->strval != NULL)
908 if (hi_surrogate != -1)
910 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
911 errmsg("invalid input syntax for type json"),
912 errdetail("Unicode low surrogate must follow a high surrogate."),
913 report_json_context(lex)));
915 appendStringInfoChar(lex->strval, *s);
920 if (hi_surrogate != -1)
922 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
923 errmsg("invalid input syntax for type json"),
924 errdetail("Unicode low surrogate must follow a high surrogate."),
925 report_json_context(lex)));
927 /* Hooray, we found the end of the string! */
928 lex->prev_token_terminator = lex->token_terminator;
929 lex->token_terminator = s + 1;
932 /*-------------------------------------------------------------------------
933 * The next token in the input stream is known to be a number; lex it.
935 * In JSON, a number consists of four parts:
937 * (1) An optional minus sign ('-').
939 * (2) Either a single '0', or a string of one or more digits that does not
942 * (3) An optional decimal part, consisting of a period ('.') followed by
943 * one or more digits. (Note: While this part can be omitted
944 * completely, it's not OK to have only the decimal point without
945 * any digits afterwards.)
947 * (4) An optional exponent part, consisting of 'e' or 'E', optionally
948 * followed by '+' or '-', followed by one or more digits. (Note:
949 * As with the decimal part, if 'e' or 'E' is present, it must be
950 * followed by at least one digit.)
952 * The 's' argument to this function points to the ostensible beginning
953 * of part 2 - i.e. the character after any optional minus sign, and the
954 * first character of the string if there is none.
956 *-------------------------------------------------------------------------
959 json_lex_number(JsonLexContext *lex, char *s, bool *num_err)
965 len = s - lex->input;
966 /* Part (1): leading sign indicator. */
967 /* Caller already did this for us; so do nothing. */
969 /* Part (2): parse main digit string. */
975 else if (*s >= '1' && *s <= '9')
981 } while (len < lex->input_length && *s >= '0' && *s <= '9');
986 /* Part (3): parse optional decimal portion. */
987 if (len < lex->input_length && *s == '.')
991 if (len == lex->input_length || *s < '0' || *s > '9')
999 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1003 /* Part (4): parse optional exponent. */
1004 if (len < lex->input_length && (*s == 'e' || *s == 'E'))
1008 if (len < lex->input_length && (*s == '+' || *s == '-'))
1013 if (len == lex->input_length || *s < '0' || *s > '9')
1021 } while (len < lex->input_length && *s >= '0' && *s <= '9');
1026 * Check for trailing garbage. As in json_lex(), any alphanumeric stuff
1027 * here should be considered part of the token for error-reporting
1030 for (p = s; len < lex->input_length && JSON_ALPHANUMERIC_CHAR(*p); p++, len++)
1033 if (num_err != NULL)
1035 /* let the caller handle the error */
1040 lex->prev_token_terminator = lex->token_terminator;
1041 lex->token_terminator = p;
1043 report_invalid_token(lex);
1048 * Report a parse error.
1050 * lex->token_start and lex->token_terminator must identify the current token.
1053 report_parse_error(JsonParseContext ctx, JsonLexContext *lex)
1058 /* Handle case where the input ended prematurely. */
1059 if (lex->token_start == NULL || lex->token_type == JSON_TOKEN_END)
1061 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1062 errmsg("invalid input syntax for type json"),
1063 errdetail("The input string ended unexpectedly."),
1064 report_json_context(lex)));
1066 /* Separate out the current token. */
1067 toklen = lex->token_terminator - lex->token_start;
1068 token = palloc(toklen + 1);
1069 memcpy(token, lex->token_start, toklen);
1070 token[toklen] = '\0';
1072 /* Complain, with the appropriate detail message. */
1073 if (ctx == JSON_PARSE_END)
1075 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1076 errmsg("invalid input syntax for type json"),
1077 errdetail("Expected end of input, but found \"%s\".",
1079 report_json_context(lex)));
1084 case JSON_PARSE_VALUE:
1086 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1087 errmsg("invalid input syntax for type json"),
1088 errdetail("Expected JSON value, but found \"%s\".",
1090 report_json_context(lex)));
1092 case JSON_PARSE_STRING:
1094 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1095 errmsg("invalid input syntax for type json"),
1096 errdetail("Expected string, but found \"%s\".",
1098 report_json_context(lex)));
1100 case JSON_PARSE_ARRAY_START:
1102 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1103 errmsg("invalid input syntax for type json"),
1104 errdetail("Expected array element or \"]\", but found \"%s\".",
1106 report_json_context(lex)));
1108 case JSON_PARSE_ARRAY_NEXT:
1110 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1111 errmsg("invalid input syntax for type json"),
1112 errdetail("Expected \",\" or \"]\", but found \"%s\".",
1114 report_json_context(lex)));
1116 case JSON_PARSE_OBJECT_START:
1118 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1119 errmsg("invalid input syntax for type json"),
1120 errdetail("Expected string or \"}\", but found \"%s\".",
1122 report_json_context(lex)));
1124 case JSON_PARSE_OBJECT_LABEL:
1126 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1127 errmsg("invalid input syntax for type json"),
1128 errdetail("Expected \":\", but found \"%s\".",
1130 report_json_context(lex)));
1132 case JSON_PARSE_OBJECT_NEXT:
1134 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1135 errmsg("invalid input syntax for type json"),
1136 errdetail("Expected \",\" or \"}\", but found \"%s\".",
1138 report_json_context(lex)));
1140 case JSON_PARSE_OBJECT_COMMA:
1142 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1143 errmsg("invalid input syntax for type json"),
1144 errdetail("Expected string, but found \"%s\".",
1146 report_json_context(lex)));
1149 elog(ERROR, "unexpected json parse state: %d", ctx);
1155 * Report an invalid input token.
1157 * lex->token_start and lex->token_terminator must identify the token.
1160 report_invalid_token(JsonLexContext *lex)
1165 /* Separate out the offending token. */
1166 toklen = lex->token_terminator - lex->token_start;
1167 token = palloc(toklen + 1);
1168 memcpy(token, lex->token_start, toklen);
1169 token[toklen] = '\0';
1172 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1173 errmsg("invalid input syntax for type json"),
1174 errdetail("Token \"%s\" is invalid.", token),
1175 report_json_context(lex)));
1179 * Report a CONTEXT line for bogus JSON input.
1181 * lex->token_terminator must be set to identify the spot where we detected
1182 * the error. Note that lex->token_start might be NULL, in case we recognized
1185 * The return value isn't meaningful, but we make it non-void so that this
1186 * can be invoked inside ereport().
1189 report_json_context(JsonLexContext *lex)
1191 const char *context_start;
1192 const char *context_end;
1193 const char *line_start;
1200 /* Choose boundaries for the part of the input we will display */
1201 context_start = lex->input;
1202 context_end = lex->token_terminator;
1203 line_start = context_start;
1207 /* Always advance over newlines */
1208 if (context_start < context_end && *context_start == '\n')
1211 line_start = context_start;
1215 /* Otherwise, done as soon as we are close enough to context_end */
1216 if (context_end - context_start < 50)
1218 /* Advance to next multibyte character */
1219 if (IS_HIGHBIT_SET(*context_start))
1220 context_start += pg_mblen(context_start);
1226 * We add "..." to indicate that the excerpt doesn't start at the
1227 * beginning of the line ... but if we're within 3 characters of the
1228 * beginning of the line, we might as well just show the whole line.
1230 if (context_start - line_start <= 3)
1231 context_start = line_start;
1233 /* Get a null-terminated copy of the data to present */
1234 ctxtlen = context_end - context_start;
1235 ctxt = palloc(ctxtlen + 1);
1236 memcpy(ctxt, context_start, ctxtlen);
1237 ctxt[ctxtlen] = '\0';
1240 * Show the context, prefixing "..." if not starting at start of line, and
1241 * suffixing "..." if not ending at end of line.
1243 prefix = (context_start > line_start) ? "..." : "";
1244 suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : "";
1246 return errcontext("JSON data, line %d: %s%s%s",
1247 line_number, prefix, ctxt, suffix);
1251 * Extract a single, possibly multi-byte char from the input string.
1254 extract_mb_char(char *s)
1260 res = palloc(len + 1);
1261 memcpy(res, s, len);
1268 * Determine how we want to print values of a given type in datum_to_json.
1270 * Given the datatype OID, return its JsonTypeCategory, as well as the type's
1271 * output function OID. If the returned category is JSONTYPE_CAST, we
1272 * return the OID of the type->JSON cast function instead.
1275 json_categorize_type(Oid typoid,
1276 JsonTypeCategory *tcategory,
1281 /* Look through any domain */
1282 typoid = getBaseType(typoid);
1284 /* We'll usually need to return the type output function */
1285 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1287 /* Check for known types */
1291 *tcategory = JSONTYPE_BOOL;
1300 *tcategory = JSONTYPE_NUMERIC;
1304 *tcategory = JSONTYPE_DATE;
1308 *tcategory = JSONTYPE_TIMESTAMP;
1311 case TIMESTAMPTZOID:
1312 *tcategory = JSONTYPE_TIMESTAMPTZ;
1317 *tcategory = JSONTYPE_JSON;
1321 /* Check for arrays and composites */
1322 if (OidIsValid(get_element_type(typoid)))
1323 *tcategory = JSONTYPE_ARRAY;
1324 else if (type_is_rowtype(typoid))
1325 *tcategory = JSONTYPE_COMPOSITE;
1328 /* It's probably the general case ... */
1329 *tcategory = JSONTYPE_OTHER;
1330 /* but let's look for a cast to json, if it's not built-in */
1331 if (typoid >= FirstNormalObjectId)
1335 tuple = SearchSysCache2(CASTSOURCETARGET,
1336 ObjectIdGetDatum(typoid),
1337 ObjectIdGetDatum(JSONOID));
1338 if (HeapTupleIsValid(tuple))
1340 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1342 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1344 *tcategory = JSONTYPE_CAST;
1345 *outfuncoid = castForm->castfunc;
1348 ReleaseSysCache(tuple);
1357 * Turn a Datum into JSON text, appending the string to "result".
1359 * tcategory and outfuncoid are from a previous call to json_categorize_type,
1360 * except that if is_null is true then they can be invalid.
1362 * If key_scalar is true, the value is being printed as a key, so insist
1363 * it's of an acceptable type, and force it to be quoted.
1366 datum_to_json(Datum val, bool is_null, StringInfo result,
1367 JsonTypeCategory tcategory, Oid outfuncoid,
1373 /* callers are expected to ensure that null keys are not passed in */
1374 Assert(!(key_scalar && is_null));
1378 appendStringInfoString(result, "null");
1383 (tcategory == JSONTYPE_ARRAY ||
1384 tcategory == JSONTYPE_COMPOSITE ||
1385 tcategory == JSONTYPE_JSON ||
1386 tcategory == JSONTYPE_CAST))
1388 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1389 errmsg("key value must be scalar, not array, composite, or json")));
1393 case JSONTYPE_ARRAY:
1394 array_to_json_internal(val, result, false);
1396 case JSONTYPE_COMPOSITE:
1397 composite_to_json(val, result, false);
1400 outputstr = DatumGetBool(val) ? "true" : "false";
1402 escape_json(result, outputstr);
1404 appendStringInfoString(result, outputstr);
1406 case JSONTYPE_NUMERIC:
1407 outputstr = OidOutputFunctionCall(outfuncoid, val);
1410 * Don't call escape_json for a non-key if it's a valid JSON
1413 if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr)))
1414 appendStringInfoString(result, outputstr);
1416 escape_json(result, outputstr);
1423 char buf[MAXDATELEN + 1];
1425 date = DatumGetDateADT(val);
1427 /* XSD doesn't support infinite values */
1428 if (DATE_NOT_FINITE(date))
1430 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1431 errmsg("date out of range"),
1432 errdetail("JSON does not support infinite date values.")));
1435 j2date(date + POSTGRES_EPOCH_JDATE,
1436 &(tm.tm_year), &(tm.tm_mon), &(tm.tm_mday));
1437 EncodeDateOnly(&tm, USE_XSD_DATES, buf);
1440 appendStringInfo(result, "\"%s\"", buf);
1443 case JSONTYPE_TIMESTAMP:
1445 Timestamp timestamp;
1448 char buf[MAXDATELEN + 1];
1450 timestamp = DatumGetTimestamp(val);
1452 /* XSD doesn't support infinite values */
1453 if (TIMESTAMP_NOT_FINITE(timestamp))
1455 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1456 errmsg("timestamp out of range"),
1457 errdetail("JSON does not support infinite timestamp values.")));
1458 else if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) == 0)
1459 EncodeDateTime(&tm, fsec, false, 0, NULL, USE_XSD_DATES, buf);
1462 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1463 errmsg("timestamp out of range")));
1465 appendStringInfo(result, "\"%s\"", buf);
1468 case JSONTYPE_TIMESTAMPTZ:
1470 TimestampTz timestamp;
1474 const char *tzn = NULL;
1475 char buf[MAXDATELEN + 1];
1477 timestamp = DatumGetTimestamp(val);
1479 /* XSD doesn't support infinite values */
1480 if (TIMESTAMP_NOT_FINITE(timestamp))
1482 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1483 errmsg("timestamp out of range"),
1484 errdetail("JSON does not support infinite timestamp values.")));
1485 else if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) == 0)
1486 EncodeDateTime(&tm, fsec, true, tz, tzn, USE_XSD_DATES, buf);
1489 (errcode(ERRCODE_DATETIME_VALUE_OUT_OF_RANGE),
1490 errmsg("timestamp out of range")));
1492 appendStringInfo(result, "\"%s\"", buf);
1496 /* JSON and JSONB output will already be escaped */
1497 outputstr = OidOutputFunctionCall(outfuncoid, val);
1498 appendStringInfoString(result, outputstr);
1502 /* outfuncoid refers to a cast function, not an output function */
1503 jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val));
1504 outputstr = text_to_cstring(jsontext);
1505 appendStringInfoString(result, outputstr);
1510 outputstr = OidOutputFunctionCall(outfuncoid, val);
1511 escape_json(result, outputstr);
1518 * Process a single dimension of an array.
1519 * If it's the innermost dimension, output the values, otherwise call
1520 * ourselves recursively to process the next dimension.
1523 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1524 bool *nulls, int *valcount, JsonTypeCategory tcategory,
1525 Oid outfuncoid, bool use_line_feeds)
1530 Assert(dim < ndims);
1532 sep = use_line_feeds ? ",\n " : ",";
1534 appendStringInfoChar(result, '[');
1536 for (i = 1; i <= dims[dim]; i++)
1539 appendStringInfoString(result, sep);
1541 if (dim + 1 == ndims)
1543 datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1550 * Do we want line feeds on inner dimensions of arrays? For now
1553 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1554 valcount, tcategory, outfuncoid, false);
1558 appendStringInfoChar(result, ']');
1562 * Turn an array into JSON.
1565 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1567 ArrayType *v = DatumGetArrayTypeP(array);
1568 Oid element_type = ARR_ELEMTYPE(v);
1578 JsonTypeCategory tcategory;
1583 nitems = ArrayGetNItems(ndim, dim);
1587 appendStringInfoString(result, "[]");
1591 get_typlenbyvalalign(element_type,
1592 &typlen, &typbyval, &typalign);
1594 json_categorize_type(element_type,
1595 &tcategory, &outfuncoid);
1597 deconstruct_array(v, element_type, typlen, typbyval,
1598 typalign, &elements, &nulls,
1601 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1602 outfuncoid, use_line_feeds);
1609 * Turn a composite / record into JSON.
1612 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1618 HeapTupleData tmptup,
1621 bool needsep = false;
1624 sep = use_line_feeds ? ",\n " : ",";
1626 td = DatumGetHeapTupleHeader(composite);
1628 /* Extract rowtype info and find a tupdesc */
1629 tupType = HeapTupleHeaderGetTypeId(td);
1630 tupTypmod = HeapTupleHeaderGetTypMod(td);
1631 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1633 /* Build a temporary HeapTuple control structure */
1634 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1638 appendStringInfoChar(result, '{');
1640 for (i = 0; i < tupdesc->natts; i++)
1645 JsonTypeCategory tcategory;
1648 if (tupdesc->attrs[i]->attisdropped)
1652 appendStringInfoString(result, sep);
1655 attname = NameStr(tupdesc->attrs[i]->attname);
1656 escape_json(result, attname);
1657 appendStringInfoChar(result, ':');
1659 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1663 tcategory = JSONTYPE_NULL;
1664 outfuncoid = InvalidOid;
1667 json_categorize_type(tupdesc->attrs[i]->atttypid,
1668 &tcategory, &outfuncoid);
1670 datum_to_json(val, isnull, result, tcategory, outfuncoid, false);
1673 appendStringInfoChar(result, '}');
1674 ReleaseTupleDesc(tupdesc);
1678 * Append JSON text for "val" to "result".
1680 * This is just a thin wrapper around datum_to_json. If the same type will be
1681 * printed many times, avoid using this; better to do the json_categorize_type
1682 * lookups only once.
1685 add_json(Datum val, bool is_null, StringInfo result,
1686 Oid val_type, bool key_scalar)
1688 JsonTypeCategory tcategory;
1691 if (val_type == InvalidOid)
1693 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1694 errmsg("could not determine input data type")));
1698 tcategory = JSONTYPE_NULL;
1699 outfuncoid = InvalidOid;
1702 json_categorize_type(val_type,
1703 &tcategory, &outfuncoid);
1705 datum_to_json(val, is_null, result, tcategory, outfuncoid, key_scalar);
1709 * SQL function array_to_json(row)
1712 array_to_json(PG_FUNCTION_ARGS)
1714 Datum array = PG_GETARG_DATUM(0);
1717 result = makeStringInfo();
1719 array_to_json_internal(array, result, false);
1721 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1725 * SQL function array_to_json(row, prettybool)
1728 array_to_json_pretty(PG_FUNCTION_ARGS)
1730 Datum array = PG_GETARG_DATUM(0);
1731 bool use_line_feeds = PG_GETARG_BOOL(1);
1734 result = makeStringInfo();
1736 array_to_json_internal(array, result, use_line_feeds);
1738 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1742 * SQL function row_to_json(row)
1745 row_to_json(PG_FUNCTION_ARGS)
1747 Datum array = PG_GETARG_DATUM(0);
1750 result = makeStringInfo();
1752 composite_to_json(array, result, false);
1754 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1758 * SQL function row_to_json(row, prettybool)
1761 row_to_json_pretty(PG_FUNCTION_ARGS)
1763 Datum array = PG_GETARG_DATUM(0);
1764 bool use_line_feeds = PG_GETARG_BOOL(1);
1767 result = makeStringInfo();
1769 composite_to_json(array, result, use_line_feeds);
1771 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1775 * SQL function to_json(anyvalue)
1778 to_json(PG_FUNCTION_ARGS)
1780 Datum val = PG_GETARG_DATUM(0);
1781 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1783 JsonTypeCategory tcategory;
1786 if (val_type == InvalidOid)
1788 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1789 errmsg("could not determine input data type")));
1791 json_categorize_type(val_type,
1792 &tcategory, &outfuncoid);
1794 result = makeStringInfo();
1796 datum_to_json(val, false, result, tcategory, outfuncoid, false);
1798 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1802 * json_agg transition function
1804 * aggregate input column as a json array value.
1807 json_agg_transfn(PG_FUNCTION_ARGS)
1809 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1810 MemoryContext aggcontext,
1814 JsonTypeCategory tcategory;
1817 if (val_type == InvalidOid)
1819 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1820 errmsg("could not determine input data type")));
1822 if (!AggCheckCallContext(fcinfo, &aggcontext))
1824 /* cannot be called directly because of internal-type argument */
1825 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1828 if (PG_ARGISNULL(0))
1831 * Make this StringInfo in a context where it will persist for the
1832 * duration of the aggregate call. MemoryContextSwitchTo is only
1833 * needed the first time, as the StringInfo routines make sure they
1834 * use the right context to enlarge the object if necessary.
1836 oldcontext = MemoryContextSwitchTo(aggcontext);
1837 state = makeStringInfo();
1838 MemoryContextSwitchTo(oldcontext);
1840 appendStringInfoChar(state, '[');
1844 state = (StringInfo) PG_GETARG_POINTER(0);
1845 appendStringInfoString(state, ", ");
1848 /* fast path for NULLs */
1849 if (PG_ARGISNULL(1))
1851 datum_to_json((Datum) 0, true, state, JSONTYPE_NULL, InvalidOid, false);
1852 PG_RETURN_POINTER(state);
1855 val = PG_GETARG_DATUM(1);
1857 /* XXX we do this every time?? */
1858 json_categorize_type(val_type,
1859 &tcategory, &outfuncoid);
1861 /* add some whitespace if structured type and not first item */
1862 if (!PG_ARGISNULL(0) &&
1863 (tcategory == JSONTYPE_ARRAY || tcategory == JSONTYPE_COMPOSITE))
1865 appendStringInfoString(state, "\n ");
1868 datum_to_json(val, false, state, tcategory, outfuncoid, false);
1871 * The transition type for array_agg() is declared to be "internal", which
1872 * is a pass-by-value type the same size as a pointer. So we can safely
1873 * pass the ArrayBuildState pointer through nodeAgg.c's machinations.
1875 PG_RETURN_POINTER(state);
1879 * json_agg final function
1882 json_agg_finalfn(PG_FUNCTION_ARGS)
1886 /* cannot be called directly because of internal-type argument */
1887 Assert(AggCheckCallContext(fcinfo, NULL));
1889 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1891 /* NULL result for no rows in, as is standard with aggregates */
1895 /* Else return state with appropriate array terminator added */
1896 PG_RETURN_TEXT_P(catenate_stringinfo_string(state, "]"));
1900 * json_object_agg transition function.
1902 * aggregate two input columns as a single json object value.
1905 json_object_agg_transfn(PG_FUNCTION_ARGS)
1908 MemoryContext aggcontext,
1913 if (!AggCheckCallContext(fcinfo, &aggcontext))
1915 /* cannot be called directly because of internal-type argument */
1916 elog(ERROR, "json_object_agg_transfn called in non-aggregate context");
1919 if (PG_ARGISNULL(0))
1922 * Make the StringInfo in a context where it will persist for the
1923 * duration of the aggregate call. Switching context is only needed
1924 * for this initial step, as the StringInfo routines make sure they
1925 * use the right context to enlarge the object if necessary.
1927 oldcontext = MemoryContextSwitchTo(aggcontext);
1928 state = makeStringInfo();
1929 MemoryContextSwitchTo(oldcontext);
1931 appendStringInfoString(state, "{ ");
1935 state = (StringInfo) PG_GETARG_POINTER(0);
1936 appendStringInfoString(state, ", ");
1940 * Note: since json_object_agg() is declared as taking type "any", the
1941 * parser will not do any type conversion on unknown-type literals (that
1942 * is, undecorated strings or NULLs). Such values will arrive here as
1943 * type UNKNOWN, which fortunately does not matter to us, since
1944 * unknownout() works fine.
1946 val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1948 if (val_type == InvalidOid)
1950 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1951 errmsg("could not determine data type for argument %d", 1)));
1953 if (PG_ARGISNULL(1))
1955 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1956 errmsg("field name must not be null")));
1958 arg = PG_GETARG_DATUM(1);
1960 add_json(arg, false, state, val_type, true);
1962 appendStringInfoString(state, " : ");
1964 val_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
1966 if (val_type == InvalidOid)
1968 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1969 errmsg("could not determine data type for argument %d", 2)));
1971 if (PG_ARGISNULL(2))
1974 arg = PG_GETARG_DATUM(2);
1976 add_json(arg, PG_ARGISNULL(2), state, val_type, false);
1978 PG_RETURN_POINTER(state);
1982 * json_object_agg final function.
1985 json_object_agg_finalfn(PG_FUNCTION_ARGS)
1989 /* cannot be called directly because of internal-type argument */
1990 Assert(AggCheckCallContext(fcinfo, NULL));
1992 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1994 /* NULL result for no rows in, as is standard with aggregates */
1998 /* Else return state with appropriate object terminator added */
1999 PG_RETURN_TEXT_P(catenate_stringinfo_string(state, " }"));
2003 * Helper function for aggregates: return given StringInfo's contents plus
2004 * specified trailing string, as a text datum. We need this because aggregate
2005 * final functions are not allowed to modify the aggregate state.
2008 catenate_stringinfo_string(StringInfo buffer, const char *addon)
2010 /* custom version of cstring_to_text_with_len */
2011 int buflen = buffer->len;
2012 int addlen = strlen(addon);
2013 text *result = (text *) palloc(buflen + addlen + VARHDRSZ);
2015 SET_VARSIZE(result, buflen + addlen + VARHDRSZ);
2016 memcpy(VARDATA(result), buffer->data, buflen);
2017 memcpy(VARDATA(result) + buflen, addon, addlen);
2023 * SQL function json_build_object(variadic "any")
2026 json_build_object(PG_FUNCTION_ARGS)
2028 int nargs = PG_NARGS();
2031 const char *sep = "";
2037 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2038 errmsg("argument list must have even number of elements"),
2039 errhint("The arguments of json_build_object() must consist of alternating keys and values.")));
2041 result = makeStringInfo();
2043 appendStringInfoChar(result, '{');
2045 for (i = 0; i < nargs; i += 2)
2048 * Note: since json_build_object() is declared as taking type "any",
2049 * the parser will not do any type conversion on unknown-type literals
2050 * (that is, undecorated strings or NULLs). Such values will arrive
2051 * here as type UNKNOWN, which fortunately does not matter to us,
2052 * since unknownout() works fine.
2054 appendStringInfoString(result, sep);
2058 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2060 if (val_type == InvalidOid)
2062 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2063 errmsg("could not determine data type for argument %d",
2066 if (PG_ARGISNULL(i))
2068 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2069 errmsg("argument %d cannot be null", i + 1),
2070 errhint("Object keys should be text.")));
2072 arg = PG_GETARG_DATUM(i);
2074 add_json(arg, false, result, val_type, true);
2076 appendStringInfoString(result, " : ");
2079 val_type = get_fn_expr_argtype(fcinfo->flinfo, i + 1);
2081 if (val_type == InvalidOid)
2083 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2084 errmsg("could not determine data type for argument %d",
2087 if (PG_ARGISNULL(i + 1))
2090 arg = PG_GETARG_DATUM(i + 1);
2092 add_json(arg, PG_ARGISNULL(i + 1), result, val_type, false);
2095 appendStringInfoChar(result, '}');
2097 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2101 * degenerate case of json_build_object where it gets 0 arguments.
2104 json_build_object_noargs(PG_FUNCTION_ARGS)
2106 PG_RETURN_TEXT_P(cstring_to_text_with_len("{}", 2));
2110 * SQL function json_build_array(variadic "any")
2113 json_build_array(PG_FUNCTION_ARGS)
2115 int nargs = PG_NARGS();
2118 const char *sep = "";
2122 result = makeStringInfo();
2124 appendStringInfoChar(result, '[');
2126 for (i = 0; i < nargs; i++)
2129 * Note: since json_build_array() is declared as taking type "any",
2130 * the parser will not do any type conversion on unknown-type literals
2131 * (that is, undecorated strings or NULLs). Such values will arrive
2132 * here as type UNKNOWN, which fortunately does not matter to us,
2133 * since unknownout() works fine.
2135 appendStringInfoString(result, sep);
2138 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2140 if (val_type == InvalidOid)
2142 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2143 errmsg("could not determine data type for argument %d",
2146 if (PG_ARGISNULL(i))
2149 arg = PG_GETARG_DATUM(i);
2151 add_json(arg, PG_ARGISNULL(i), result, val_type, false);
2154 appendStringInfoChar(result, ']');
2156 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2160 * degenerate case of json_build_array where it gets 0 arguments.
2163 json_build_array_noargs(PG_FUNCTION_ARGS)
2165 PG_RETURN_TEXT_P(cstring_to_text_with_len("[]", 2));
2169 * SQL function json_object(text[])
2171 * take a one or two dimensional array of text as key/value pairs
2172 * for a json object.
2175 json_object(PG_FUNCTION_ARGS)
2177 ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
2178 int ndims = ARR_NDIM(in_array);
2179 StringInfoData result;
2191 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2195 if ((ARR_DIMS(in_array)[0]) % 2)
2197 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2198 errmsg("array must have even number of elements")));
2202 if ((ARR_DIMS(in_array)[1]) != 2)
2204 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2205 errmsg("array must have two columns")));
2210 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2211 errmsg("wrong number of array subscripts")));
2214 deconstruct_array(in_array,
2215 TEXTOID, -1, false, 'i',
2216 &in_datums, &in_nulls, &in_count);
2218 count = in_count / 2;
2220 initStringInfo(&result);
2222 appendStringInfoChar(&result, '{');
2224 for (i = 0; i < count; ++i)
2226 if (in_nulls[i * 2])
2228 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2229 errmsg("null value not allowed for object key")));
2231 v = TextDatumGetCString(in_datums[i * 2]);
2233 appendStringInfoString(&result, ", ");
2234 escape_json(&result, v);
2235 appendStringInfoString(&result, " : ");
2237 if (in_nulls[i * 2 + 1])
2238 appendStringInfoString(&result, "null");
2241 v = TextDatumGetCString(in_datums[i * 2 + 1]);
2242 escape_json(&result, v);
2247 appendStringInfoChar(&result, '}');
2252 rval = cstring_to_text_with_len(result.data, result.len);
2255 PG_RETURN_TEXT_P(rval);
2260 * SQL function json_object(text[], text[])
2262 * take separate key and value arrays of text to construct a json object
2266 json_object_two_arg(PG_FUNCTION_ARGS)
2268 ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
2269 ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
2270 int nkdims = ARR_NDIM(key_array);
2271 int nvdims = ARR_NDIM(val_array);
2272 StringInfoData result;
2283 if (nkdims > 1 || nkdims != nvdims)
2285 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2286 errmsg("wrong number of array subscripts")));
2289 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2291 deconstruct_array(key_array,
2292 TEXTOID, -1, false, 'i',
2293 &key_datums, &key_nulls, &key_count);
2295 deconstruct_array(val_array,
2296 TEXTOID, -1, false, 'i',
2297 &val_datums, &val_nulls, &val_count);
2299 if (key_count != val_count)
2301 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2302 errmsg("mismatched array dimensions")));
2304 initStringInfo(&result);
2306 appendStringInfoChar(&result, '{');
2308 for (i = 0; i < key_count; ++i)
2312 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2313 errmsg("null value not allowed for object key")));
2315 v = TextDatumGetCString(key_datums[i]);
2317 appendStringInfoString(&result, ", ");
2318 escape_json(&result, v);
2319 appendStringInfoString(&result, " : ");
2322 appendStringInfoString(&result, "null");
2325 v = TextDatumGetCString(val_datums[i]);
2326 escape_json(&result, v);
2331 appendStringInfoChar(&result, '}');
2338 rval = cstring_to_text_with_len(result.data, result.len);
2341 PG_RETURN_TEXT_P(rval);
2346 * Produce a JSON string literal, properly escaping characters in the text.
2349 escape_json(StringInfo buf, const char *str)
2353 appendStringInfoCharMacro(buf, '\"');
2354 for (p = str; *p; p++)
2359 appendStringInfoString(buf, "\\b");
2362 appendStringInfoString(buf, "\\f");
2365 appendStringInfoString(buf, "\\n");
2368 appendStringInfoString(buf, "\\r");
2371 appendStringInfoString(buf, "\\t");
2374 appendStringInfoString(buf, "\\\"");
2379 * Unicode escapes are passed through as is. There is no
2380 * requirement that they denote a valid character in the
2381 * server encoding - indeed that is a big part of their
2384 * All we require is that they consist of \uXXXX where the Xs
2385 * are hexadecimal digits. It is the responsibility of the
2386 * caller of, say, to_json() to make sure that the unicode
2389 * In the case of a jsonb string value being escaped, the only
2390 * unicode escape that should be present is \u0000, all the
2391 * other unicode escapes will have been resolved.
2394 isxdigit((unsigned char) p[2]) &&
2395 isxdigit((unsigned char) p[3]) &&
2396 isxdigit((unsigned char) p[4]) &&
2397 isxdigit((unsigned char) p[5]))
2398 appendStringInfoCharMacro(buf, *p);
2400 appendStringInfoString(buf, "\\\\");
2403 if ((unsigned char) *p < ' ')
2404 appendStringInfo(buf, "\\u%04x", (int) *p);
2406 appendStringInfoCharMacro(buf, *p);
2410 appendStringInfoCharMacro(buf, '\"');
2414 * SQL function json_typeof(json) -> text
2416 * Returns the type of the outermost JSON value as TEXT. Possible types are
2417 * "object", "array", "string", "number", "boolean", and "null".
2419 * Performs a single call to json_lex() to get the first token of the supplied
2420 * value. This initial token uniquely determines the value's type. As our
2421 * input must already have been validated by json_in() or json_recv(), the
2422 * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
2423 * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
2426 json_typeof(PG_FUNCTION_ARGS)
2430 JsonLexContext *lex;
2434 json = PG_GETARG_TEXT_P(0);
2435 lex = makeJsonLexContext(json, false);
2437 /* Lex exactly one token from the input and check its type. */
2439 tok = lex_peek(lex);
2442 case JSON_TOKEN_OBJECT_START:
2445 case JSON_TOKEN_ARRAY_START:
2448 case JSON_TOKEN_STRING:
2451 case JSON_TOKEN_NUMBER:
2454 case JSON_TOKEN_TRUE:
2455 case JSON_TOKEN_FALSE:
2458 case JSON_TOKEN_NULL:
2462 elog(ERROR, "unexpected json token: %d", tok);
2465 PG_RETURN_TEXT_P(cstring_to_text(type));