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 "parser/parse_coerce.h"
25 #include "utils/array.h"
26 #include "utils/builtins.h"
27 #include "utils/lsyscache.h"
28 #include "utils/json.h"
29 #include "utils/jsonapi.h"
30 #include "utils/typcache.h"
31 #include "utils/syscache.h"
34 * The context of the parser is maintained by the recursive descent
35 * mechanism, but is passed explicitly to the error reporting routine
36 * for better diagnostics.
38 typedef enum /* contexts of JSON parser */
40 JSON_PARSE_VALUE, /* expecting a value */
41 JSON_PARSE_STRING, /* expecting a string (for a field name) */
42 JSON_PARSE_ARRAY_START, /* saw '[', expecting value or ']' */
43 JSON_PARSE_ARRAY_NEXT, /* saw array element, expecting ',' or ']' */
44 JSON_PARSE_OBJECT_START, /* saw '{', expecting label or '}' */
45 JSON_PARSE_OBJECT_LABEL, /* saw object label, expecting ':' */
46 JSON_PARSE_OBJECT_NEXT, /* saw object value, expecting ',' or '}' */
47 JSON_PARSE_OBJECT_COMMA, /* saw object ',', expecting next label */
48 JSON_PARSE_END /* saw the end of a document, expect nothing */
51 static inline void json_lex(JsonLexContext *lex);
52 static inline void json_lex_string(JsonLexContext *lex);
53 static inline void json_lex_number(JsonLexContext *lex, char *s, bool *num_err);
54 static inline void parse_scalar(JsonLexContext *lex, JsonSemAction *sem);
55 static void parse_object_field(JsonLexContext *lex, JsonSemAction *sem);
56 static void parse_object(JsonLexContext *lex, JsonSemAction *sem);
57 static void parse_array_element(JsonLexContext *lex, JsonSemAction *sem);
58 static void parse_array(JsonLexContext *lex, JsonSemAction *sem);
59 static void report_parse_error(JsonParseContext ctx, JsonLexContext *lex);
60 static void report_invalid_token(JsonLexContext *lex);
61 static int report_json_context(JsonLexContext *lex);
62 static char *extract_mb_char(char *s);
63 static void composite_to_json(Datum composite, StringInfo result,
65 static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
66 Datum *vals, bool *nulls, int *valcount,
67 TYPCATEGORY tcategory, Oid typoutputfunc,
69 static void array_to_json_internal(Datum array, StringInfo result,
72 /* the null action object used for pure validation */
73 static JsonSemAction nullSemAction =
75 NULL, NULL, NULL, NULL, NULL,
76 NULL, NULL, NULL, NULL, NULL
79 /* Recursive Descent parser support routines */
84 * what is the current look_ahead token?
86 static inline JsonTokenType
87 lex_peek(JsonLexContext *lex)
89 return lex->token_type;
95 * accept the look_ahead token and move the lexer to the next token if the
96 * look_ahead token matches the token parameter. In that case, and if required,
97 * also hand back the de-escaped lexeme.
99 * returns true if the token matched, false otherwise.
102 lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
104 if (lex->token_type == token)
108 if (lex->token_type == JSON_TOKEN_STRING)
110 if (lex->strval != NULL)
111 *lexeme = pstrdup(lex->strval->data);
115 int len = (lex->token_terminator - lex->token_start);
116 char *tokstr = palloc(len + 1);
118 memcpy(tokstr, lex->token_start, len);
132 * move the lexer to the next token if the current look_ahead token matches
133 * the parameter token. Otherwise, report an error.
136 lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
138 if (!lex_accept(lex, token, NULL))
139 report_parse_error(ctx, lex);;
143 * All the defined type categories are upper case , so use lower case here
144 * so we avoid any possible clash.
146 /* fake type category for JSON so we can distinguish it in datum_to_json */
147 #define TYPCATEGORY_JSON 'j'
148 /* fake category for types that have a cast to json */
149 #define TYPCATEGORY_JSON_CAST 'c'
150 /* chars to consider as part of an alphanumeric token */
151 #define JSON_ALPHANUMERIC_CHAR(c) \
152 (((c) >= 'a' && (c) <= 'z') || \
153 ((c) >= 'A' && (c) <= 'Z') || \
154 ((c) >= '0' && (c) <= '9') || \
162 json_in(PG_FUNCTION_ARGS)
164 char *json = PG_GETARG_CSTRING(0);
165 text *result = cstring_to_text(json);
169 lex = makeJsonLexContext(result, false);
170 pg_parse_json(lex, &nullSemAction);
172 /* Internal representation is the same as text, for now */
173 PG_RETURN_TEXT_P(result);
180 json_out(PG_FUNCTION_ARGS)
182 /* we needn't detoast because text_to_cstring will handle that */
183 Datum txt = PG_GETARG_DATUM(0);
185 PG_RETURN_CSTRING(TextDatumGetCString(txt));
192 json_send(PG_FUNCTION_ARGS)
194 text *t = PG_GETARG_TEXT_PP(0);
197 pq_begintypsend(&buf);
198 pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
199 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
206 json_recv(PG_FUNCTION_ARGS)
208 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
214 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
216 result = palloc(nbytes + VARHDRSZ);
217 SET_VARSIZE(result, nbytes + VARHDRSZ);
218 memcpy(VARDATA(result), str, nbytes);
221 lex = makeJsonLexContext(result, false);
222 pg_parse_json(lex, &nullSemAction);
224 PG_RETURN_TEXT_P(result);
230 * lex constructor, with or without StringInfo object
231 * for de-escaped lexemes.
233 * Without is better as it makes the processing faster, so only make one
234 * if really required.
237 makeJsonLexContext(text *json, bool need_escapes)
239 JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
241 lex->input = lex->token_terminator = lex->line_start = VARDATA(json);
242 lex->line_number = 1;
243 lex->input_length = VARSIZE(json) - VARHDRSZ;
245 lex->strval = makeStringInfo();
252 * Publicly visible entry point for the JSON parser.
254 * lex is a lexing context, set up for the json to be processed by calling
255 * makeJsonLexContext(). sem is a strucure of function pointers to semantic
256 * action routines to be called at appropriate spots during parsing, and a
257 * pointer to a state object to be passed to those routines.
260 pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
264 /* get the initial token */
269 /* parse by recursive descent */
272 case JSON_TOKEN_OBJECT_START:
273 parse_object(lex, sem);
275 case JSON_TOKEN_ARRAY_START:
276 parse_array(lex, sem);
279 parse_scalar(lex, sem); /* json can be a bare scalar */
282 lex_expect(JSON_PARSE_END, lex, JSON_TOKEN_END);
287 * Recursive Descent parse routines. There is one for each structural
288 * element in a json document:
289 * - scalar (string, number, true, false, null)
296 parse_scalar(JsonLexContext *lex, JsonSemAction *sem)
299 json_scalar_action sfunc = sem->scalar;
301 JsonTokenType tok = lex_peek(lex);
303 valaddr = sfunc == NULL ? NULL : &val;
305 /* a scalar must be a string, a number, true, false, or null */
308 case JSON_TOKEN_TRUE:
309 lex_accept(lex, JSON_TOKEN_TRUE, valaddr);
311 case JSON_TOKEN_FALSE:
312 lex_accept(lex, JSON_TOKEN_FALSE, valaddr);
314 case JSON_TOKEN_NULL:
315 lex_accept(lex, JSON_TOKEN_NULL, valaddr);
317 case JSON_TOKEN_NUMBER:
318 lex_accept(lex, JSON_TOKEN_NUMBER, valaddr);
320 case JSON_TOKEN_STRING:
321 lex_accept(lex, JSON_TOKEN_STRING, valaddr);
324 report_parse_error(JSON_PARSE_VALUE, lex);
328 (*sfunc) (sem->semstate, val, tok);
332 parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
335 * an object field is "fieldname" : value where value can be a scalar,
339 char *fname = NULL; /* keep compiler quiet */
340 json_ofield_action ostart = sem->object_field_start;
341 json_ofield_action oend = sem->object_field_end;
343 char **fnameaddr = NULL;
346 if (ostart != NULL || oend != NULL)
349 if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
350 report_parse_error(JSON_PARSE_STRING, lex);
352 lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
355 isnull = tok == JSON_TOKEN_NULL;
358 (*ostart) (sem->semstate, fname, isnull);
362 case JSON_TOKEN_OBJECT_START:
363 parse_object(lex, sem);
365 case JSON_TOKEN_ARRAY_START:
366 parse_array(lex, sem);
369 parse_scalar(lex, sem);
373 (*oend) (sem->semstate, fname, isnull);
380 parse_object(JsonLexContext *lex, JsonSemAction *sem)
383 * an object is a possibly empty sequence of object fields, separated by
384 * commas and surrounde by curly braces.
386 json_struct_action ostart = sem->object_start;
387 json_struct_action oend = sem->object_end;
391 (*ostart) (sem->semstate);
394 * Data inside an object at at a higher nesting level than the object
395 * itself. Note that we increment this after we call the semantic routine
396 * for the object start and restore it before we call the routine for the
401 /* we know this will succeeed, just clearing the token */
402 lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
407 case JSON_TOKEN_STRING:
408 parse_object_field(lex, sem);
409 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
410 parse_object_field(lex, sem);
412 case JSON_TOKEN_OBJECT_END:
415 /* case of an invalid initial token inside the object */
416 report_parse_error(JSON_PARSE_OBJECT_START, lex);
419 lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
424 (*oend) (sem->semstate);
428 parse_array_element(JsonLexContext *lex, JsonSemAction *sem)
430 json_aelem_action astart = sem->array_element_start;
431 json_aelem_action aend = sem->array_element_end;
432 JsonTokenType tok = lex_peek(lex);
436 isnull = tok == JSON_TOKEN_NULL;
439 (*astart) (sem->semstate, isnull);
441 /* an array element is any object, array or scalar */
444 case JSON_TOKEN_OBJECT_START:
445 parse_object(lex, sem);
447 case JSON_TOKEN_ARRAY_START:
448 parse_array(lex, sem);
451 parse_scalar(lex, sem);
455 (*aend) (sem->semstate, isnull);
459 parse_array(JsonLexContext *lex, JsonSemAction *sem)
462 * an array is a possibly empty sequence of array elements, separated by
463 * commas and surrounded by square brackets.
465 json_struct_action astart = sem->array_start;
466 json_struct_action aend = sem->array_end;
469 (*astart) (sem->semstate);
472 * Data inside an array at at a higher nesting level than the array
473 * itself. Note that we increment this after we call the semantic routine
474 * for the array start and restore it before we call the routine for the
479 lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
480 if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
483 parse_array_element(lex, sem);
485 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
486 parse_array_element(lex, sem);
489 lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
494 (*aend) (sem->semstate);
498 * Lex one token from the input stream.
501 json_lex(JsonLexContext *lex)
506 /* Skip leading whitespace. */
507 s = lex->token_terminator;
508 len = s - lex->input;
509 while (len < lex->input_length &&
510 (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
517 lex->token_start = s;
519 /* Determine token type. */
520 if (len >= lex->input_length)
522 lex->token_start = NULL;
523 lex->prev_token_terminator = lex->token_terminator;
524 lex->token_terminator = s;
525 lex->token_type = JSON_TOKEN_END;
530 /* Single-character token, some kind of punctuation mark. */
532 lex->prev_token_terminator = lex->token_terminator;
533 lex->token_terminator = s + 1;
534 lex->token_type = JSON_TOKEN_OBJECT_START;
537 lex->prev_token_terminator = lex->token_terminator;
538 lex->token_terminator = s + 1;
539 lex->token_type = JSON_TOKEN_OBJECT_END;
542 lex->prev_token_terminator = lex->token_terminator;
543 lex->token_terminator = s + 1;
544 lex->token_type = JSON_TOKEN_ARRAY_START;
547 lex->prev_token_terminator = lex->token_terminator;
548 lex->token_terminator = s + 1;
549 lex->token_type = JSON_TOKEN_ARRAY_END;
552 lex->prev_token_terminator = lex->token_terminator;
553 lex->token_terminator = s + 1;
554 lex->token_type = JSON_TOKEN_COMMA;
557 lex->prev_token_terminator = lex->token_terminator;
558 lex->token_terminator = s + 1;
559 lex->token_type = JSON_TOKEN_COLON;
563 json_lex_string(lex);
564 lex->token_type = JSON_TOKEN_STRING;
567 /* Negative number. */
568 json_lex_number(lex, s + 1, NULL);
569 lex->token_type = JSON_TOKEN_NUMBER;
581 /* Positive number. */
582 json_lex_number(lex, s, NULL);
583 lex->token_type = JSON_TOKEN_NUMBER;
590 * We're not dealing with a string, number, legal
591 * punctuation mark, or end of string. The only legal
592 * tokens we might find here are true, false, and null,
593 * but for error reporting purposes we scan until we see a
594 * non-alphanumeric character. That way, we can report
595 * the whole word as an unexpected token, rather than just
596 * some unintuitive prefix thereof.
598 for (p = s; p - s < lex->input_length - len && JSON_ALPHANUMERIC_CHAR(*p); p++)
602 * We got some sort of unexpected punctuation or an
603 * otherwise unexpected character, so just complain about
604 * that one character.
608 lex->prev_token_terminator = lex->token_terminator;
609 lex->token_terminator = s + 1;
610 report_invalid_token(lex);
614 * We've got a real alphanumeric token here. If it
615 * happens to be true, false, or null, all is well. If
618 lex->prev_token_terminator = lex->token_terminator;
619 lex->token_terminator = p;
622 if (memcmp(s, "true", 4) == 0)
623 lex->token_type = JSON_TOKEN_TRUE;
624 else if (memcmp(s, "null", 4) == 0)
625 lex->token_type = JSON_TOKEN_NULL;
627 report_invalid_token(lex);
629 else if (p - s == 5 && memcmp(s, "false", 5) == 0)
630 lex->token_type = JSON_TOKEN_FALSE;
632 report_invalid_token(lex);
635 } /* end of switch */
639 * The next token in the input stream is known to be a string; lex it.
642 json_lex_string(JsonLexContext *lex)
646 int hi_surrogate = -1;
648 if (lex->strval != NULL)
649 resetStringInfo(lex->strval);
651 Assert(lex->input_length > 0);
652 s = lex->token_start;
653 len = lex->token_start - lex->input;
658 /* Premature end of the string. */
659 if (len >= lex->input_length)
661 lex->token_terminator = s;
662 report_invalid_token(lex);
666 else if ((unsigned char) *s < 32)
668 /* Per RFC4627, these characters MUST be escaped. */
669 /* Since *s isn't printable, exclude it from the context string */
670 lex->token_terminator = s;
672 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
673 errmsg("invalid input syntax for type json"),
674 errdetail("Character with value 0x%02x must be escaped.",
676 report_json_context(lex)));
680 /* OK, we have an escape character. */
683 if (len >= lex->input_length)
685 lex->token_terminator = s;
686 report_invalid_token(lex);
693 for (i = 1; i <= 4; i++)
697 if (len >= lex->input_length)
699 lex->token_terminator = s;
700 report_invalid_token(lex);
702 else if (*s >= '0' && *s <= '9')
703 ch = (ch * 16) + (*s - '0');
704 else if (*s >= 'a' && *s <= 'f')
705 ch = (ch * 16) + (*s - 'a') + 10;
706 else if (*s >= 'A' && *s <= 'F')
707 ch = (ch * 16) + (*s - 'A') + 10;
710 lex->token_terminator = s + pg_mblen(s);
712 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
713 errmsg("invalid input syntax for type json"),
714 errdetail("\"\\u\" must be followed by four hexadecimal digits."),
715 report_json_context(lex)));
718 if (lex->strval != NULL)
723 if (ch >= 0xd800 && ch <= 0xdbff)
725 if (hi_surrogate != -1)
727 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
728 errmsg("invalid input syntax for type json"),
729 errdetail("Unicode high surrogate must not follow a high surrogate."),
730 report_json_context(lex)));
731 hi_surrogate = (ch & 0x3ff) << 10;
734 else if (ch >= 0xdc00 && ch <= 0xdfff)
736 if (hi_surrogate == -1)
738 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
739 errmsg("invalid input syntax for type json"),
740 errdetail("Unicode low surrogate must follow a high surrogate."),
741 report_json_context(lex)));
742 ch = 0x10000 + hi_surrogate + (ch & 0x3ff);
746 if (hi_surrogate != -1)
748 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
749 errmsg("invalid input syntax for type json"),
750 errdetail("Unicode low surrogate must follow a high surrogate."),
751 report_json_context(lex)));
754 * For UTF8, replace the escape sequence by the actual
755 * utf8 character in lex->strval. Do this also for other
756 * encodings if the escape designates an ASCII character,
757 * otherwise raise an error. We don't ever unescape a
758 * \u0000, since that would result in an impermissible nul
764 appendStringInfoString(lex->strval, "\\u0000");
766 else if (GetDatabaseEncoding() == PG_UTF8)
768 unicode_to_utf8(ch, (unsigned char *) utf8str);
769 utf8len = pg_utf_mblen((unsigned char *) utf8str);
770 appendBinaryStringInfo(lex->strval, utf8str, utf8len);
772 else if (ch <= 0x007f)
775 * This is the only way to designate things like a
776 * form feed character in JSON, so it's useful in all
779 appendStringInfoChar(lex->strval, (char) ch);
784 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
785 errmsg("invalid input syntax for type json"),
786 errdetail("Unicode escape values cannot be used for code point values above 007F when the server encoding is not UTF8."),
787 report_json_context(lex)));
792 else if (lex->strval != NULL)
794 if (hi_surrogate != -1)
796 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
797 errmsg("invalid input syntax for type json"),
798 errdetail("Unicode low surrogate must follow a high surrogate."),
799 report_json_context(lex)));
806 appendStringInfoChar(lex->strval, *s);
809 appendStringInfoChar(lex->strval, '\b');
812 appendStringInfoChar(lex->strval, '\f');
815 appendStringInfoChar(lex->strval, '\n');
818 appendStringInfoChar(lex->strval, '\r');
821 appendStringInfoChar(lex->strval, '\t');
824 /* Not a valid string escape, so error out. */
825 lex->token_terminator = s + pg_mblen(s);
827 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
828 errmsg("invalid input syntax for type json"),
829 errdetail("Escape sequence \"\\%s\" is invalid.",
831 report_json_context(lex)));
834 else if (strchr("\"\\/bfnrt", *s) == NULL)
837 * Simpler processing if we're not bothered about de-escaping
839 * It's very tempting to remove the strchr() call here and
840 * replace it with a switch statement, but testing so far has
841 * shown it's not a performance win.
843 lex->token_terminator = s + pg_mblen(s);
845 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
846 errmsg("invalid input syntax for type json"),
847 errdetail("Escape sequence \"\\%s\" is invalid.",
849 report_json_context(lex)));
853 else if (lex->strval != NULL)
855 if (hi_surrogate != -1)
857 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
858 errmsg("invalid input syntax for type json"),
859 errdetail("Unicode low surrogate must follow a high surrogate."),
860 report_json_context(lex)));
862 appendStringInfoChar(lex->strval, *s);
867 if (hi_surrogate != -1)
869 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
870 errmsg("invalid input syntax for type json"),
871 errdetail("Unicode low surrogate must follow a high surrogate."),
872 report_json_context(lex)));
874 /* Hooray, we found the end of the string! */
875 lex->prev_token_terminator = lex->token_terminator;
876 lex->token_terminator = s + 1;
879 /*-------------------------------------------------------------------------
880 * The next token in the input stream is known to be a number; lex it.
882 * In JSON, a number consists of four parts:
884 * (1) An optional minus sign ('-').
886 * (2) Either a single '0', or a string of one or more digits that does not
889 * (3) An optional decimal part, consisting of a period ('.') followed by
890 * one or more digits. (Note: While this part can be omitted
891 * completely, it's not OK to have only the decimal point without
892 * any digits afterwards.)
894 * (4) An optional exponent part, consisting of 'e' or 'E', optionally
895 * followed by '+' or '-', followed by one or more digits. (Note:
896 * As with the decimal part, if 'e' or 'E' is present, it must be
897 * followed by at least one digit.)
899 * The 's' argument to this function points to the ostensible beginning
900 * of part 2 - i.e. the character after any optional minus sign, and the
901 * first character of the string if there is none.
903 *-------------------------------------------------------------------------
906 json_lex_number(JsonLexContext *lex, char *s, bool *num_err)
912 len = s - lex->input;
913 /* Part (1): leading sign indicator. */
914 /* Caller already did this for us; so do nothing. */
916 /* Part (2): parse main digit string. */
922 else if (*s >= '1' && *s <= '9')
928 } while (len < lex->input_length && *s >= '0' && *s <= '9');
933 /* Part (3): parse optional decimal portion. */
934 if (len < lex->input_length && *s == '.')
938 if (len == lex->input_length || *s < '0' || *s > '9')
946 } while (len < lex->input_length && *s >= '0' && *s <= '9');
950 /* Part (4): parse optional exponent. */
951 if (len < lex->input_length && (*s == 'e' || *s == 'E'))
955 if (len < lex->input_length && (*s == '+' || *s == '-'))
960 if (len == lex->input_length || *s < '0' || *s > '9')
968 } while (len < lex->input_length && *s >= '0' && *s <= '9');
973 * Check for trailing garbage. As in json_lex(), any alphanumeric stuff
974 * here should be considered part of the token for error-reporting
977 for (p = s; len < lex->input_length && JSON_ALPHANUMERIC_CHAR(*p); p++, len++)
982 /* let the caller handle the error */
987 lex->prev_token_terminator = lex->token_terminator;
988 lex->token_terminator = p;
990 report_invalid_token(lex);
995 * Report a parse error.
997 * lex->token_start and lex->token_terminator must identify the current token.
1000 report_parse_error(JsonParseContext ctx, JsonLexContext *lex)
1005 /* Handle case where the input ended prematurely. */
1006 if (lex->token_start == NULL || lex->token_type == JSON_TOKEN_END)
1008 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1009 errmsg("invalid input syntax for type json"),
1010 errdetail("The input string ended unexpectedly."),
1011 report_json_context(lex)));
1013 /* Separate out the current token. */
1014 toklen = lex->token_terminator - lex->token_start;
1015 token = palloc(toklen + 1);
1016 memcpy(token, lex->token_start, toklen);
1017 token[toklen] = '\0';
1019 /* Complain, with the appropriate detail message. */
1020 if (ctx == JSON_PARSE_END)
1022 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1023 errmsg("invalid input syntax for type json"),
1024 errdetail("Expected end of input, but found \"%s\".",
1026 report_json_context(lex)));
1031 case JSON_PARSE_VALUE:
1033 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1034 errmsg("invalid input syntax for type json"),
1035 errdetail("Expected JSON value, but found \"%s\".",
1037 report_json_context(lex)));
1039 case JSON_PARSE_STRING:
1041 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1042 errmsg("invalid input syntax for type json"),
1043 errdetail("Expected string, but found \"%s\".",
1045 report_json_context(lex)));
1047 case JSON_PARSE_ARRAY_START:
1049 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1050 errmsg("invalid input syntax for type json"),
1051 errdetail("Expected array element or \"]\", but found \"%s\".",
1053 report_json_context(lex)));
1055 case JSON_PARSE_ARRAY_NEXT:
1057 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1058 errmsg("invalid input syntax for type json"),
1059 errdetail("Expected \",\" or \"]\", but found \"%s\".",
1061 report_json_context(lex)));
1063 case JSON_PARSE_OBJECT_START:
1065 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1066 errmsg("invalid input syntax for type json"),
1067 errdetail("Expected string or \"}\", but found \"%s\".",
1069 report_json_context(lex)));
1071 case JSON_PARSE_OBJECT_LABEL:
1073 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1074 errmsg("invalid input syntax for type json"),
1075 errdetail("Expected \":\", but found \"%s\".",
1077 report_json_context(lex)));
1079 case JSON_PARSE_OBJECT_NEXT:
1081 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1082 errmsg("invalid input syntax for type json"),
1083 errdetail("Expected \",\" or \"}\", but found \"%s\".",
1085 report_json_context(lex)));
1087 case JSON_PARSE_OBJECT_COMMA:
1089 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1090 errmsg("invalid input syntax for type json"),
1091 errdetail("Expected string, but found \"%s\".",
1093 report_json_context(lex)));
1096 elog(ERROR, "unexpected json parse state: %d", ctx);
1102 * Report an invalid input token.
1104 * lex->token_start and lex->token_terminator must identify the token.
1107 report_invalid_token(JsonLexContext *lex)
1112 /* Separate out the offending token. */
1113 toklen = lex->token_terminator - lex->token_start;
1114 token = palloc(toklen + 1);
1115 memcpy(token, lex->token_start, toklen);
1116 token[toklen] = '\0';
1119 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1120 errmsg("invalid input syntax for type json"),
1121 errdetail("Token \"%s\" is invalid.", token),
1122 report_json_context(lex)));
1126 * Report a CONTEXT line for bogus JSON input.
1128 * lex->token_terminator must be set to identify the spot where we detected
1129 * the error. Note that lex->token_start might be NULL, in case we recognized
1132 * The return value isn't meaningful, but we make it non-void so that this
1133 * can be invoked inside ereport().
1136 report_json_context(JsonLexContext *lex)
1138 const char *context_start;
1139 const char *context_end;
1140 const char *line_start;
1147 /* Choose boundaries for the part of the input we will display */
1148 context_start = lex->input;
1149 context_end = lex->token_terminator;
1150 line_start = context_start;
1154 /* Always advance over newlines */
1155 if (context_start < context_end && *context_start == '\n')
1158 line_start = context_start;
1162 /* Otherwise, done as soon as we are close enough to context_end */
1163 if (context_end - context_start < 50)
1165 /* Advance to next multibyte character */
1166 if (IS_HIGHBIT_SET(*context_start))
1167 context_start += pg_mblen(context_start);
1173 * We add "..." to indicate that the excerpt doesn't start at the
1174 * beginning of the line ... but if we're within 3 characters of the
1175 * beginning of the line, we might as well just show the whole line.
1177 if (context_start - line_start <= 3)
1178 context_start = line_start;
1180 /* Get a null-terminated copy of the data to present */
1181 ctxtlen = context_end - context_start;
1182 ctxt = palloc(ctxtlen + 1);
1183 memcpy(ctxt, context_start, ctxtlen);
1184 ctxt[ctxtlen] = '\0';
1187 * Show the context, prefixing "..." if not starting at start of line, and
1188 * suffixing "..." if not ending at end of line.
1190 prefix = (context_start > line_start) ? "..." : "";
1191 suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : "";
1193 return errcontext("JSON data, line %d: %s%s%s",
1194 line_number, prefix, ctxt, suffix);
1198 * Extract a single, possibly multi-byte char from the input string.
1201 extract_mb_char(char *s)
1207 res = palloc(len + 1);
1208 memcpy(res, s, len);
1215 * Turn a scalar Datum into JSON, appending the string to "result".
1217 * Hand off a non-scalar datum to composite_to_json or array_to_json_internal
1221 datum_to_json(Datum val, bool is_null, StringInfo result,
1222 TYPCATEGORY tcategory, Oid typoutputfunc)
1227 JsonLexContext dummy_lex;
1231 appendStringInfoString(result, "null");
1237 case TYPCATEGORY_ARRAY:
1238 array_to_json_internal(val, result, false);
1240 case TYPCATEGORY_COMPOSITE:
1241 composite_to_json(val, result, false);
1243 case TYPCATEGORY_BOOLEAN:
1244 if (DatumGetBool(val))
1245 appendStringInfoString(result, "true");
1247 appendStringInfoString(result, "false");
1249 case TYPCATEGORY_NUMERIC:
1250 outputstr = OidOutputFunctionCall(typoutputfunc, val);
1253 * Don't call escape_json here if it's a valid JSON number.
1255 dummy_lex.input = *outputstr == '-' ? outputstr + 1 : outputstr;
1256 dummy_lex.input_length = strlen(dummy_lex.input);
1257 json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error);
1259 appendStringInfoString(result, outputstr);
1261 escape_json(result, outputstr);
1264 case TYPCATEGORY_JSON:
1265 /* JSON will already be escaped */
1266 outputstr = OidOutputFunctionCall(typoutputfunc, val);
1267 appendStringInfoString(result, outputstr);
1270 case TYPCATEGORY_JSON_CAST:
1271 jsontext = DatumGetTextP(OidFunctionCall1(typoutputfunc, val));
1272 outputstr = text_to_cstring(jsontext);
1273 appendStringInfoString(result, outputstr);
1278 outputstr = OidOutputFunctionCall(typoutputfunc, val);
1279 escape_json(result, outputstr);
1286 * Process a single dimension of an array.
1287 * If it's the innermost dimension, output the values, otherwise call
1288 * ourselves recursively to process the next dimension.
1291 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1292 bool *nulls, int *valcount, TYPCATEGORY tcategory,
1293 Oid typoutputfunc, bool use_line_feeds)
1298 Assert(dim < ndims);
1300 sep = use_line_feeds ? ",\n " : ",";
1302 appendStringInfoChar(result, '[');
1304 for (i = 1; i <= dims[dim]; i++)
1307 appendStringInfoString(result, sep);
1309 if (dim + 1 == ndims)
1311 datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1318 * Do we want line feeds on inner dimensions of arrays? For now
1321 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1322 valcount, tcategory, typoutputfunc, false);
1326 appendStringInfoChar(result, ']');
1330 * Turn an array into JSON.
1333 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1335 ArrayType *v = DatumGetArrayTypeP(array);
1336 Oid element_type = ARR_ELEMTYPE(v);
1349 TYPCATEGORY tcategory;
1350 Oid castfunc = InvalidOid;
1354 nitems = ArrayGetNItems(ndim, dim);
1358 appendStringInfoString(result, "[]");
1362 get_type_io_data(element_type, IOFunc_output,
1363 &typlen, &typbyval, &typalign,
1364 &typdelim, &typioparam, &typoutputfunc);
1366 if (element_type > FirstNormalObjectId)
1369 Form_pg_cast castForm;
1371 tuple = SearchSysCache2(CASTSOURCETARGET,
1372 ObjectIdGetDatum(element_type),
1373 ObjectIdGetDatum(JSONOID));
1374 if (HeapTupleIsValid(tuple))
1376 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1378 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1379 castfunc = typoutputfunc = castForm->castfunc;
1381 ReleaseSysCache(tuple);
1385 deconstruct_array(v, element_type, typlen, typbyval,
1386 typalign, &elements, &nulls,
1389 if (castfunc != InvalidOid)
1390 tcategory = TYPCATEGORY_JSON_CAST;
1391 else if (element_type == RECORDOID)
1392 tcategory = TYPCATEGORY_COMPOSITE;
1393 else if (element_type == JSONOID)
1394 tcategory = TYPCATEGORY_JSON;
1396 tcategory = TypeCategory(element_type);
1398 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1399 typoutputfunc, use_line_feeds);
1406 * Turn a composite / record into JSON.
1409 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1415 HeapTupleData tmptup,
1418 bool needsep = false;
1421 sep = use_line_feeds ? ",\n " : ",";
1423 td = DatumGetHeapTupleHeader(composite);
1425 /* Extract rowtype info and find a tupdesc */
1426 tupType = HeapTupleHeaderGetTypeId(td);
1427 tupTypmod = HeapTupleHeaderGetTypMod(td);
1428 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1430 /* Build a temporary HeapTuple control structure */
1431 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1435 appendStringInfoChar(result, '{');
1437 for (i = 0; i < tupdesc->natts; i++)
1442 TYPCATEGORY tcategory;
1445 Oid castfunc = InvalidOid;
1447 if (tupdesc->attrs[i]->attisdropped)
1451 appendStringInfoString(result, sep);
1454 attname = NameStr(tupdesc->attrs[i]->attname);
1455 escape_json(result, attname);
1456 appendStringInfoChar(result, ':');
1458 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1460 getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
1461 &typoutput, &typisvarlena);
1463 if (tupdesc->attrs[i]->atttypid > FirstNormalObjectId)
1465 HeapTuple cast_tuple;
1466 Form_pg_cast castForm;
1468 cast_tuple = SearchSysCache2(CASTSOURCETARGET,
1469 ObjectIdGetDatum(tupdesc->attrs[i]->atttypid),
1470 ObjectIdGetDatum(JSONOID));
1471 if (HeapTupleIsValid(cast_tuple))
1473 castForm = (Form_pg_cast) GETSTRUCT(cast_tuple);
1475 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1476 castfunc = typoutput = castForm->castfunc;
1478 ReleaseSysCache(cast_tuple);
1482 if (castfunc != InvalidOid)
1483 tcategory = TYPCATEGORY_JSON_CAST;
1484 else if (tupdesc->attrs[i]->atttypid == RECORDARRAYOID)
1485 tcategory = TYPCATEGORY_ARRAY;
1486 else if (tupdesc->attrs[i]->atttypid == RECORDOID)
1487 tcategory = TYPCATEGORY_COMPOSITE;
1488 else if (tupdesc->attrs[i]->atttypid == JSONOID)
1489 tcategory = TYPCATEGORY_JSON;
1491 tcategory = TypeCategory(tupdesc->attrs[i]->atttypid);
1493 datum_to_json(val, isnull, result, tcategory, typoutput);
1496 appendStringInfoChar(result, '}');
1497 ReleaseTupleDesc(tupdesc);
1501 * SQL function array_to_json(row)
1504 array_to_json(PG_FUNCTION_ARGS)
1506 Datum array = PG_GETARG_DATUM(0);
1509 result = makeStringInfo();
1511 array_to_json_internal(array, result, false);
1513 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1517 * SQL function array_to_json(row, prettybool)
1520 array_to_json_pretty(PG_FUNCTION_ARGS)
1522 Datum array = PG_GETARG_DATUM(0);
1523 bool use_line_feeds = PG_GETARG_BOOL(1);
1526 result = makeStringInfo();
1528 array_to_json_internal(array, result, use_line_feeds);
1530 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1534 * SQL function row_to_json(row)
1537 row_to_json(PG_FUNCTION_ARGS)
1539 Datum array = PG_GETARG_DATUM(0);
1542 result = makeStringInfo();
1544 composite_to_json(array, result, false);
1546 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1550 * SQL function row_to_json(row, prettybool)
1553 row_to_json_pretty(PG_FUNCTION_ARGS)
1555 Datum array = PG_GETARG_DATUM(0);
1556 bool use_line_feeds = PG_GETARG_BOOL(1);
1559 result = makeStringInfo();
1561 composite_to_json(array, result, use_line_feeds);
1563 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1567 * SQL function to_json(anyvalue)
1570 to_json(PG_FUNCTION_ARGS)
1572 Datum val = PG_GETARG_DATUM(0);
1573 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1575 TYPCATEGORY tcategory;
1578 Oid castfunc = InvalidOid;
1580 if (val_type == InvalidOid)
1582 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1583 errmsg("could not determine input data type")));
1585 result = makeStringInfo();
1587 getTypeOutputInfo(val_type, &typoutput, &typisvarlena);
1589 if (val_type > FirstNormalObjectId)
1592 Form_pg_cast castForm;
1594 tuple = SearchSysCache2(CASTSOURCETARGET,
1595 ObjectIdGetDatum(val_type),
1596 ObjectIdGetDatum(JSONOID));
1597 if (HeapTupleIsValid(tuple))
1599 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1601 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1602 castfunc = typoutput = castForm->castfunc;
1604 ReleaseSysCache(tuple);
1608 if (castfunc != InvalidOid)
1609 tcategory = TYPCATEGORY_JSON_CAST;
1610 else if (val_type == RECORDARRAYOID)
1611 tcategory = TYPCATEGORY_ARRAY;
1612 else if (val_type == RECORDOID)
1613 tcategory = TYPCATEGORY_COMPOSITE;
1614 else if (val_type == JSONOID)
1615 tcategory = TYPCATEGORY_JSON;
1617 tcategory = TypeCategory(val_type);
1619 datum_to_json(val, false, result, tcategory, typoutput);
1621 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1625 * json_agg transition function
1628 json_agg_transfn(PG_FUNCTION_ARGS)
1630 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1631 MemoryContext aggcontext,
1635 TYPCATEGORY tcategory;
1638 Oid castfunc = InvalidOid;
1640 if (val_type == InvalidOid)
1642 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1643 errmsg("could not determine input data type")));
1645 if (!AggCheckCallContext(fcinfo, &aggcontext))
1647 /* cannot be called directly because of internal-type argument */
1648 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1651 if (PG_ARGISNULL(0))
1654 * Make this StringInfo in a context where it will persist for the
1655 * duration off the aggregate call. It's only needed for this initial
1656 * piece, as the StringInfo routines make sure they use the right
1657 * context to enlarge the object if necessary.
1659 oldcontext = MemoryContextSwitchTo(aggcontext);
1660 state = makeStringInfo();
1661 MemoryContextSwitchTo(oldcontext);
1663 appendStringInfoChar(state, '[');
1667 state = (StringInfo) PG_GETARG_POINTER(0);
1668 appendStringInfoString(state, ", ");
1671 /* fast path for NULLs */
1672 if (PG_ARGISNULL(1))
1675 datum_to_json(val, true, state, 0, InvalidOid);
1676 PG_RETURN_POINTER(state);
1679 val = PG_GETARG_DATUM(1);
1681 getTypeOutputInfo(val_type, &typoutput, &typisvarlena);
1683 if (val_type > FirstNormalObjectId)
1686 Form_pg_cast castForm;
1688 tuple = SearchSysCache2(CASTSOURCETARGET,
1689 ObjectIdGetDatum(val_type),
1690 ObjectIdGetDatum(JSONOID));
1691 if (HeapTupleIsValid(tuple))
1693 castForm = (Form_pg_cast) GETSTRUCT(tuple);
1695 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1696 castfunc = typoutput = castForm->castfunc;
1698 ReleaseSysCache(tuple);
1702 if (castfunc != InvalidOid)
1703 tcategory = TYPCATEGORY_JSON_CAST;
1704 else if (val_type == RECORDARRAYOID)
1705 tcategory = TYPCATEGORY_ARRAY;
1706 else if (val_type == RECORDOID)
1707 tcategory = TYPCATEGORY_COMPOSITE;
1708 else if (val_type == JSONOID)
1709 tcategory = TYPCATEGORY_JSON;
1711 tcategory = TypeCategory(val_type);
1713 if (!PG_ARGISNULL(0) &&
1714 (tcategory == TYPCATEGORY_ARRAY || tcategory == TYPCATEGORY_COMPOSITE))
1716 appendStringInfoString(state, "\n ");
1719 datum_to_json(val, false, state, tcategory, typoutput);
1722 * The transition type for array_agg() is declared to be "internal", which
1723 * is a pass-by-value type the same size as a pointer. So we can safely
1724 * pass the ArrayBuildState pointer through nodeAgg.c's machinations.
1726 PG_RETURN_POINTER(state);
1730 * json_agg final function
1733 json_agg_finalfn(PG_FUNCTION_ARGS)
1737 /* cannot be called directly because of internal-type argument */
1738 Assert(AggCheckCallContext(fcinfo, NULL));
1740 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1745 appendStringInfoChar(state, ']');
1747 PG_RETURN_TEXT_P(cstring_to_text_with_len(state->data, state->len));
1751 * Produce a JSON string literal, properly escaping characters in the text.
1754 escape_json(StringInfo buf, const char *str)
1758 appendStringInfoCharMacro(buf, '\"');
1759 for (p = str; *p; p++)
1764 appendStringInfoString(buf, "\\b");
1767 appendStringInfoString(buf, "\\f");
1770 appendStringInfoString(buf, "\\n");
1773 appendStringInfoString(buf, "\\r");
1776 appendStringInfoString(buf, "\\t");
1779 appendStringInfoString(buf, "\\\"");
1782 appendStringInfoString(buf, "\\\\");
1785 if ((unsigned char) *p < ' ')
1786 appendStringInfo(buf, "\\u%04x", (int) *p);
1788 appendStringInfoCharMacro(buf, *p);
1792 appendStringInfoCharMacro(buf, '\"');
1796 * SQL function json_typeof(json) -> text
1798 * Returns the type of the outermost JSON value as TEXT. Possible types are
1799 * "object", "array", "string", "number", "boolean", and "null".
1801 * Performs a single call to json_lex() to get the first token of the supplied
1802 * value. This initial token uniquely determines the value's type. As our
1803 * input must already have been validated by json_in() or json_recv(), the
1804 * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
1805 * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
1808 json_typeof(PG_FUNCTION_ARGS)
1810 text *json = PG_GETARG_TEXT_P(0);
1812 JsonLexContext *lex = makeJsonLexContext(json, false);
1816 /* Lex exactly one token from the input and check its type. */
1818 tok = lex_peek(lex);
1821 case JSON_TOKEN_OBJECT_START:
1824 case JSON_TOKEN_ARRAY_START:
1827 case JSON_TOKEN_STRING:
1830 case JSON_TOKEN_NUMBER:
1833 case JSON_TOKEN_TRUE:
1834 case JSON_TOKEN_FALSE:
1837 case JSON_TOKEN_NULL:
1841 elog(ERROR, "unexpected json token: %d", tok);
1844 PG_RETURN_TEXT_P(cstring_to_text(type));