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/formatting.h"
28 #include "utils/lsyscache.h"
29 #include "utils/json.h"
30 #include "utils/jsonapi.h"
31 #include "utils/typcache.h"
32 #include "utils/syscache.h"
35 * The context of the parser is maintained by the recursive descent
36 * mechanism, but is passed explicitly to the error reporting routine
37 * for better diagnostics.
39 typedef enum /* contexts of JSON parser */
41 JSON_PARSE_VALUE, /* expecting a value */
42 JSON_PARSE_STRING, /* expecting a string (for a field name) */
43 JSON_PARSE_ARRAY_START, /* saw '[', expecting value or ']' */
44 JSON_PARSE_ARRAY_NEXT, /* saw array element, expecting ',' or ']' */
45 JSON_PARSE_OBJECT_START, /* saw '{', expecting label or '}' */
46 JSON_PARSE_OBJECT_LABEL, /* saw object label, expecting ':' */
47 JSON_PARSE_OBJECT_NEXT, /* saw object value, expecting ',' or '}' */
48 JSON_PARSE_OBJECT_COMMA, /* saw object ',', expecting next label */
49 JSON_PARSE_END /* saw the end of a document, expect nothing */
52 typedef enum /* type categories for datum_to_json */
54 JSONTYPE_NULL, /* null, so we didn't bother to identify */
55 JSONTYPE_BOOL, /* boolean (built-in types only) */
56 JSONTYPE_NUMERIC, /* numeric (ditto) */
57 JSONTYPE_TIMESTAMP, /* we use special formatting for timestamp */
58 JSONTYPE_TIMESTAMPTZ, /* ... and timestamptz */
59 JSONTYPE_JSON, /* JSON itself (and JSONB) */
60 JSONTYPE_ARRAY, /* array */
61 JSONTYPE_COMPOSITE, /* composite */
62 JSONTYPE_CAST, /* something with an explicit cast to JSON */
63 JSONTYPE_OTHER /* all else */
67 * to_char formats to turn timestamps and timpstamptzs into json strings
68 * that are ISO 8601 compliant
70 #define TS_ISO8601_FMT "\\\"YYYY-MM-DD\"T\"HH24:MI:SS.US\\\""
71 #define TSTZ_ISO8601_FMT "\\\"YYYY-MM-DD\"T\"HH24:MI:SS.USOF\\\""
73 static inline void json_lex(JsonLexContext *lex);
74 static inline void json_lex_string(JsonLexContext *lex);
75 static inline void json_lex_number(JsonLexContext *lex, char *s, bool *num_err);
76 static inline void parse_scalar(JsonLexContext *lex, JsonSemAction *sem);
77 static void parse_object_field(JsonLexContext *lex, JsonSemAction *sem);
78 static void parse_object(JsonLexContext *lex, JsonSemAction *sem);
79 static void parse_array_element(JsonLexContext *lex, JsonSemAction *sem);
80 static void parse_array(JsonLexContext *lex, JsonSemAction *sem);
81 static void report_parse_error(JsonParseContext ctx, JsonLexContext *lex);
82 static void report_invalid_token(JsonLexContext *lex);
83 static int report_json_context(JsonLexContext *lex);
84 static char *extract_mb_char(char *s);
85 static void composite_to_json(Datum composite, StringInfo result,
87 static void array_dim_to_json(StringInfo result, int dim, int ndims, int *dims,
88 Datum *vals, bool *nulls, int *valcount,
89 JsonTypeCategory tcategory, Oid outfuncoid,
91 static void array_to_json_internal(Datum array, StringInfo result,
93 static void json_categorize_type(Oid typoid,
94 JsonTypeCategory *tcategory,
96 static void datum_to_json(Datum val, bool is_null, StringInfo result,
97 JsonTypeCategory tcategory, Oid outfuncoid,
99 static void add_json(Datum val, bool is_null, StringInfo result,
100 Oid val_type, bool key_scalar);
102 /* the null action object used for pure validation */
103 static JsonSemAction nullSemAction =
105 NULL, NULL, NULL, NULL, NULL,
106 NULL, NULL, NULL, NULL, NULL
109 /* Recursive Descent parser support routines */
114 * what is the current look_ahead token?
116 static inline JsonTokenType
117 lex_peek(JsonLexContext *lex)
119 return lex->token_type;
125 * accept the look_ahead token and move the lexer to the next token if the
126 * look_ahead token matches the token parameter. In that case, and if required,
127 * also hand back the de-escaped lexeme.
129 * returns true if the token matched, false otherwise.
132 lex_accept(JsonLexContext *lex, JsonTokenType token, char **lexeme)
134 if (lex->token_type == token)
138 if (lex->token_type == JSON_TOKEN_STRING)
140 if (lex->strval != NULL)
141 *lexeme = pstrdup(lex->strval->data);
145 int len = (lex->token_terminator - lex->token_start);
146 char *tokstr = palloc(len + 1);
148 memcpy(tokstr, lex->token_start, len);
162 * move the lexer to the next token if the current look_ahead token matches
163 * the parameter token. Otherwise, report an error.
166 lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
168 if (!lex_accept(lex, token, NULL))
169 report_parse_error(ctx, lex);;
172 /* chars to consider as part of an alphanumeric token */
173 #define JSON_ALPHANUMERIC_CHAR(c) \
174 (((c) >= 'a' && (c) <= 'z') || \
175 ((c) >= 'A' && (c) <= 'Z') || \
176 ((c) >= '0' && (c) <= '9') || \
184 json_in(PG_FUNCTION_ARGS)
186 char *json = PG_GETARG_CSTRING(0);
187 text *result = cstring_to_text(json);
191 lex = makeJsonLexContext(result, false);
192 pg_parse_json(lex, &nullSemAction);
194 /* Internal representation is the same as text, for now */
195 PG_RETURN_TEXT_P(result);
202 json_out(PG_FUNCTION_ARGS)
204 /* we needn't detoast because text_to_cstring will handle that */
205 Datum txt = PG_GETARG_DATUM(0);
207 PG_RETURN_CSTRING(TextDatumGetCString(txt));
214 json_send(PG_FUNCTION_ARGS)
216 text *t = PG_GETARG_TEXT_PP(0);
219 pq_begintypsend(&buf);
220 pq_sendtext(&buf, VARDATA_ANY(t), VARSIZE_ANY_EXHDR(t));
221 PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
228 json_recv(PG_FUNCTION_ARGS)
230 StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
235 str = pq_getmsgtext(buf, buf->len - buf->cursor, &nbytes);
238 lex = makeJsonLexContextCstringLen(str, nbytes, false);
239 pg_parse_json(lex, &nullSemAction);
241 PG_RETURN_TEXT_P(cstring_to_text_with_len(str, nbytes));
247 * lex constructor, with or without StringInfo object
248 * for de-escaped lexemes.
250 * Without is better as it makes the processing faster, so only make one
251 * if really required.
253 * If you already have the json as a text* value, use the first of these
254 * functions, otherwise use makeJsonLexContextCstringLen().
257 makeJsonLexContext(text *json, bool need_escapes)
259 return makeJsonLexContextCstringLen(VARDATA(json),
260 VARSIZE(json) - VARHDRSZ,
265 makeJsonLexContextCstringLen(char *json, int len, bool need_escapes)
267 JsonLexContext *lex = palloc0(sizeof(JsonLexContext));
269 lex->input = lex->token_terminator = lex->line_start = json;
270 lex->line_number = 1;
271 lex->input_length = len;
273 lex->strval = makeStringInfo();
280 * Publicly visible entry point for the JSON parser.
282 * lex is a lexing context, set up for the json to be processed by calling
283 * makeJsonLexContext(). sem is a strucure of function pointers to semantic
284 * action routines to be called at appropriate spots during parsing, and a
285 * pointer to a state object to be passed to those routines.
288 pg_parse_json(JsonLexContext *lex, JsonSemAction *sem)
292 /* get the initial token */
297 /* parse by recursive descent */
300 case JSON_TOKEN_OBJECT_START:
301 parse_object(lex, sem);
303 case JSON_TOKEN_ARRAY_START:
304 parse_array(lex, sem);
307 parse_scalar(lex, sem); /* json can be a bare scalar */
310 lex_expect(JSON_PARSE_END, lex, JSON_TOKEN_END);
315 * Recursive Descent parse routines. There is one for each structural
316 * element in a json document:
317 * - scalar (string, number, true, false, null)
324 parse_scalar(JsonLexContext *lex, JsonSemAction *sem)
327 json_scalar_action sfunc = sem->scalar;
329 JsonTokenType tok = lex_peek(lex);
331 valaddr = sfunc == NULL ? NULL : &val;
333 /* a scalar must be a string, a number, true, false, or null */
336 case JSON_TOKEN_TRUE:
337 lex_accept(lex, JSON_TOKEN_TRUE, valaddr);
339 case JSON_TOKEN_FALSE:
340 lex_accept(lex, JSON_TOKEN_FALSE, valaddr);
342 case JSON_TOKEN_NULL:
343 lex_accept(lex, JSON_TOKEN_NULL, valaddr);
345 case JSON_TOKEN_NUMBER:
346 lex_accept(lex, JSON_TOKEN_NUMBER, valaddr);
348 case JSON_TOKEN_STRING:
349 lex_accept(lex, JSON_TOKEN_STRING, valaddr);
352 report_parse_error(JSON_PARSE_VALUE, lex);
356 (*sfunc) (sem->semstate, val, tok);
360 parse_object_field(JsonLexContext *lex, JsonSemAction *sem)
363 * an object field is "fieldname" : value where value can be a scalar,
367 char *fname = NULL; /* keep compiler quiet */
368 json_ofield_action ostart = sem->object_field_start;
369 json_ofield_action oend = sem->object_field_end;
371 char **fnameaddr = NULL;
374 if (ostart != NULL || oend != NULL)
377 if (!lex_accept(lex, JSON_TOKEN_STRING, fnameaddr))
378 report_parse_error(JSON_PARSE_STRING, lex);
380 lex_expect(JSON_PARSE_OBJECT_LABEL, lex, JSON_TOKEN_COLON);
383 isnull = tok == JSON_TOKEN_NULL;
386 (*ostart) (sem->semstate, fname, isnull);
390 case JSON_TOKEN_OBJECT_START:
391 parse_object(lex, sem);
393 case JSON_TOKEN_ARRAY_START:
394 parse_array(lex, sem);
397 parse_scalar(lex, sem);
401 (*oend) (sem->semstate, fname, isnull);
405 parse_object(JsonLexContext *lex, JsonSemAction *sem)
408 * an object is a possibly empty sequence of object fields, separated by
409 * commas and surrounde by curly braces.
411 json_struct_action ostart = sem->object_start;
412 json_struct_action oend = sem->object_end;
416 (*ostart) (sem->semstate);
419 * Data inside an object is at a higher nesting level than the object
420 * itself. Note that we increment this after we call the semantic routine
421 * for the object start and restore it before we call the routine for the
426 /* we know this will succeeed, just clearing the token */
427 lex_expect(JSON_PARSE_OBJECT_START, lex, JSON_TOKEN_OBJECT_START);
432 case JSON_TOKEN_STRING:
433 parse_object_field(lex, sem);
434 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
435 parse_object_field(lex, sem);
437 case JSON_TOKEN_OBJECT_END:
440 /* case of an invalid initial token inside the object */
441 report_parse_error(JSON_PARSE_OBJECT_START, lex);
444 lex_expect(JSON_PARSE_OBJECT_NEXT, lex, JSON_TOKEN_OBJECT_END);
449 (*oend) (sem->semstate);
453 parse_array_element(JsonLexContext *lex, JsonSemAction *sem)
455 json_aelem_action astart = sem->array_element_start;
456 json_aelem_action aend = sem->array_element_end;
457 JsonTokenType tok = lex_peek(lex);
461 isnull = tok == JSON_TOKEN_NULL;
464 (*astart) (sem->semstate, isnull);
466 /* an array element is any object, array or scalar */
469 case JSON_TOKEN_OBJECT_START:
470 parse_object(lex, sem);
472 case JSON_TOKEN_ARRAY_START:
473 parse_array(lex, sem);
476 parse_scalar(lex, sem);
480 (*aend) (sem->semstate, isnull);
484 parse_array(JsonLexContext *lex, JsonSemAction *sem)
487 * an array is a possibly empty sequence of array elements, separated by
488 * commas and surrounded by square brackets.
490 json_struct_action astart = sem->array_start;
491 json_struct_action aend = sem->array_end;
494 (*astart) (sem->semstate);
497 * Data inside an array is at a higher nesting level than the array
498 * itself. Note that we increment this after we call the semantic routine
499 * for the array start and restore it before we call the routine for the
504 lex_expect(JSON_PARSE_ARRAY_START, lex, JSON_TOKEN_ARRAY_START);
505 if (lex_peek(lex) != JSON_TOKEN_ARRAY_END)
508 parse_array_element(lex, sem);
510 while (lex_accept(lex, JSON_TOKEN_COMMA, NULL))
511 parse_array_element(lex, sem);
514 lex_expect(JSON_PARSE_ARRAY_NEXT, lex, JSON_TOKEN_ARRAY_END);
519 (*aend) (sem->semstate);
523 * Lex one token from the input stream.
526 json_lex(JsonLexContext *lex)
531 /* Skip leading whitespace. */
532 s = lex->token_terminator;
533 len = s - lex->input;
534 while (len < lex->input_length &&
535 (*s == ' ' || *s == '\t' || *s == '\n' || *s == '\r'))
542 lex->token_start = s;
544 /* Determine token type. */
545 if (len >= lex->input_length)
547 lex->token_start = NULL;
548 lex->prev_token_terminator = lex->token_terminator;
549 lex->token_terminator = s;
550 lex->token_type = JSON_TOKEN_END;
555 /* Single-character token, some kind of punctuation mark. */
557 lex->prev_token_terminator = lex->token_terminator;
558 lex->token_terminator = s + 1;
559 lex->token_type = JSON_TOKEN_OBJECT_START;
562 lex->prev_token_terminator = lex->token_terminator;
563 lex->token_terminator = s + 1;
564 lex->token_type = JSON_TOKEN_OBJECT_END;
567 lex->prev_token_terminator = lex->token_terminator;
568 lex->token_terminator = s + 1;
569 lex->token_type = JSON_TOKEN_ARRAY_START;
572 lex->prev_token_terminator = lex->token_terminator;
573 lex->token_terminator = s + 1;
574 lex->token_type = JSON_TOKEN_ARRAY_END;
577 lex->prev_token_terminator = lex->token_terminator;
578 lex->token_terminator = s + 1;
579 lex->token_type = JSON_TOKEN_COMMA;
582 lex->prev_token_terminator = lex->token_terminator;
583 lex->token_terminator = s + 1;
584 lex->token_type = JSON_TOKEN_COLON;
588 json_lex_string(lex);
589 lex->token_type = JSON_TOKEN_STRING;
592 /* Negative number. */
593 json_lex_number(lex, s + 1, NULL);
594 lex->token_type = JSON_TOKEN_NUMBER;
606 /* Positive number. */
607 json_lex_number(lex, s, NULL);
608 lex->token_type = JSON_TOKEN_NUMBER;
615 * We're not dealing with a string, number, legal
616 * punctuation mark, or end of string. The only legal
617 * tokens we might find here are true, false, and null,
618 * but for error reporting purposes we scan until we see a
619 * non-alphanumeric character. That way, we can report
620 * the whole word as an unexpected token, rather than just
621 * some unintuitive prefix thereof.
623 for (p = s; p - s < lex->input_length - len && JSON_ALPHANUMERIC_CHAR(*p); p++)
627 * We got some sort of unexpected punctuation or an
628 * otherwise unexpected character, so just complain about
629 * that one character.
633 lex->prev_token_terminator = lex->token_terminator;
634 lex->token_terminator = s + 1;
635 report_invalid_token(lex);
639 * We've got a real alphanumeric token here. If it
640 * happens to be true, false, or null, all is well. If
643 lex->prev_token_terminator = lex->token_terminator;
644 lex->token_terminator = p;
647 if (memcmp(s, "true", 4) == 0)
648 lex->token_type = JSON_TOKEN_TRUE;
649 else if (memcmp(s, "null", 4) == 0)
650 lex->token_type = JSON_TOKEN_NULL;
652 report_invalid_token(lex);
654 else if (p - s == 5 && memcmp(s, "false", 5) == 0)
655 lex->token_type = JSON_TOKEN_FALSE;
657 report_invalid_token(lex);
660 } /* end of switch */
664 * The next token in the input stream is known to be a string; lex it.
667 json_lex_string(JsonLexContext *lex)
671 int hi_surrogate = -1;
673 if (lex->strval != NULL)
674 resetStringInfo(lex->strval);
676 Assert(lex->input_length > 0);
677 s = lex->token_start;
678 len = lex->token_start - lex->input;
683 /* Premature end of the string. */
684 if (len >= lex->input_length)
686 lex->token_terminator = s;
687 report_invalid_token(lex);
691 else if ((unsigned char) *s < 32)
693 /* Per RFC4627, these characters MUST be escaped. */
694 /* Since *s isn't printable, exclude it from the context string */
695 lex->token_terminator = s;
697 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
698 errmsg("invalid input syntax for type json"),
699 errdetail("Character with value 0x%02x must be escaped.",
701 report_json_context(lex)));
705 /* OK, we have an escape character. */
708 if (len >= lex->input_length)
710 lex->token_terminator = s;
711 report_invalid_token(lex);
718 for (i = 1; i <= 4; i++)
722 if (len >= lex->input_length)
724 lex->token_terminator = s;
725 report_invalid_token(lex);
727 else if (*s >= '0' && *s <= '9')
728 ch = (ch * 16) + (*s - '0');
729 else if (*s >= 'a' && *s <= 'f')
730 ch = (ch * 16) + (*s - 'a') + 10;
731 else if (*s >= 'A' && *s <= 'F')
732 ch = (ch * 16) + (*s - 'A') + 10;
735 lex->token_terminator = s + pg_mblen(s);
737 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
738 errmsg("invalid input syntax for type json"),
739 errdetail("\"\\u\" must be followed by four hexadecimal digits."),
740 report_json_context(lex)));
743 if (lex->strval != NULL)
748 if (ch >= 0xd800 && ch <= 0xdbff)
750 if (hi_surrogate != -1)
752 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
753 errmsg("invalid input syntax for type json"),
754 errdetail("Unicode high surrogate must not follow a high surrogate."),
755 report_json_context(lex)));
756 hi_surrogate = (ch & 0x3ff) << 10;
759 else if (ch >= 0xdc00 && ch <= 0xdfff)
761 if (hi_surrogate == -1)
763 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
764 errmsg("invalid input syntax for type json"),
765 errdetail("Unicode low surrogate must follow a high surrogate."),
766 report_json_context(lex)));
767 ch = 0x10000 + hi_surrogate + (ch & 0x3ff);
771 if (hi_surrogate != -1)
773 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
774 errmsg("invalid input syntax for type json"),
775 errdetail("Unicode low surrogate must follow a high surrogate."),
776 report_json_context(lex)));
779 * For UTF8, replace the escape sequence by the actual
780 * utf8 character in lex->strval. Do this also for other
781 * encodings if the escape designates an ASCII character,
782 * otherwise raise an error. We don't ever unescape a
783 * \u0000, since that would result in an impermissible nul
789 appendStringInfoString(lex->strval, "\\u0000");
791 else if (GetDatabaseEncoding() == PG_UTF8)
793 unicode_to_utf8(ch, (unsigned char *) utf8str);
794 utf8len = pg_utf_mblen((unsigned char *) utf8str);
795 appendBinaryStringInfo(lex->strval, utf8str, utf8len);
797 else if (ch <= 0x007f)
800 * This is the only way to designate things like a
801 * form feed character in JSON, so it's useful in all
804 appendStringInfoChar(lex->strval, (char) ch);
809 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
810 errmsg("invalid input syntax for type json"),
811 errdetail("Unicode escape values cannot be used for code point values above 007F when the server encoding is not UTF8."),
812 report_json_context(lex)));
817 else if (lex->strval != NULL)
819 if (hi_surrogate != -1)
821 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
822 errmsg("invalid input syntax for type json"),
823 errdetail("Unicode low surrogate must follow a high surrogate."),
824 report_json_context(lex)));
831 appendStringInfoChar(lex->strval, *s);
834 appendStringInfoChar(lex->strval, '\b');
837 appendStringInfoChar(lex->strval, '\f');
840 appendStringInfoChar(lex->strval, '\n');
843 appendStringInfoChar(lex->strval, '\r');
846 appendStringInfoChar(lex->strval, '\t');
849 /* Not a valid string escape, so error out. */
850 lex->token_terminator = s + pg_mblen(s);
852 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
853 errmsg("invalid input syntax for type json"),
854 errdetail("Escape sequence \"\\%s\" is invalid.",
856 report_json_context(lex)));
859 else if (strchr("\"\\/bfnrt", *s) == NULL)
862 * Simpler processing if we're not bothered about de-escaping
864 * It's very tempting to remove the strchr() call here and
865 * replace it with a switch statement, but testing so far has
866 * shown it's not a performance win.
868 lex->token_terminator = s + pg_mblen(s);
870 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
871 errmsg("invalid input syntax for type json"),
872 errdetail("Escape sequence \"\\%s\" is invalid.",
874 report_json_context(lex)));
878 else if (lex->strval != NULL)
880 if (hi_surrogate != -1)
882 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
883 errmsg("invalid input syntax for type json"),
884 errdetail("Unicode low surrogate must follow a high surrogate."),
885 report_json_context(lex)));
887 appendStringInfoChar(lex->strval, *s);
892 if (hi_surrogate != -1)
894 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
895 errmsg("invalid input syntax for type json"),
896 errdetail("Unicode low surrogate must follow a high surrogate."),
897 report_json_context(lex)));
899 /* Hooray, we found the end of the string! */
900 lex->prev_token_terminator = lex->token_terminator;
901 lex->token_terminator = s + 1;
904 /*-------------------------------------------------------------------------
905 * The next token in the input stream is known to be a number; lex it.
907 * In JSON, a number consists of four parts:
909 * (1) An optional minus sign ('-').
911 * (2) Either a single '0', or a string of one or more digits that does not
914 * (3) An optional decimal part, consisting of a period ('.') followed by
915 * one or more digits. (Note: While this part can be omitted
916 * completely, it's not OK to have only the decimal point without
917 * any digits afterwards.)
919 * (4) An optional exponent part, consisting of 'e' or 'E', optionally
920 * followed by '+' or '-', followed by one or more digits. (Note:
921 * As with the decimal part, if 'e' or 'E' is present, it must be
922 * followed by at least one digit.)
924 * The 's' argument to this function points to the ostensible beginning
925 * of part 2 - i.e. the character after any optional minus sign, and the
926 * first character of the string if there is none.
928 *-------------------------------------------------------------------------
931 json_lex_number(JsonLexContext *lex, char *s, bool *num_err)
937 len = s - lex->input;
938 /* Part (1): leading sign indicator. */
939 /* Caller already did this for us; so do nothing. */
941 /* Part (2): parse main digit string. */
947 else if (*s >= '1' && *s <= '9')
953 } while (len < lex->input_length && *s >= '0' && *s <= '9');
958 /* Part (3): parse optional decimal portion. */
959 if (len < lex->input_length && *s == '.')
963 if (len == lex->input_length || *s < '0' || *s > '9')
971 } while (len < lex->input_length && *s >= '0' && *s <= '9');
975 /* Part (4): parse optional exponent. */
976 if (len < lex->input_length && (*s == 'e' || *s == 'E'))
980 if (len < lex->input_length && (*s == '+' || *s == '-'))
985 if (len == lex->input_length || *s < '0' || *s > '9')
993 } while (len < lex->input_length && *s >= '0' && *s <= '9');
998 * Check for trailing garbage. As in json_lex(), any alphanumeric stuff
999 * here should be considered part of the token for error-reporting
1002 for (p = s; len < lex->input_length && JSON_ALPHANUMERIC_CHAR(*p); p++, len++)
1005 if (num_err != NULL)
1007 /* let the caller handle the error */
1012 lex->prev_token_terminator = lex->token_terminator;
1013 lex->token_terminator = p;
1015 report_invalid_token(lex);
1020 * Report a parse error.
1022 * lex->token_start and lex->token_terminator must identify the current token.
1025 report_parse_error(JsonParseContext ctx, JsonLexContext *lex)
1030 /* Handle case where the input ended prematurely. */
1031 if (lex->token_start == NULL || lex->token_type == JSON_TOKEN_END)
1033 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1034 errmsg("invalid input syntax for type json"),
1035 errdetail("The input string ended unexpectedly."),
1036 report_json_context(lex)));
1038 /* Separate out the current token. */
1039 toklen = lex->token_terminator - lex->token_start;
1040 token = palloc(toklen + 1);
1041 memcpy(token, lex->token_start, toklen);
1042 token[toklen] = '\0';
1044 /* Complain, with the appropriate detail message. */
1045 if (ctx == JSON_PARSE_END)
1047 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1048 errmsg("invalid input syntax for type json"),
1049 errdetail("Expected end of input, but found \"%s\".",
1051 report_json_context(lex)));
1056 case JSON_PARSE_VALUE:
1058 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1059 errmsg("invalid input syntax for type json"),
1060 errdetail("Expected JSON value, but found \"%s\".",
1062 report_json_context(lex)));
1064 case JSON_PARSE_STRING:
1066 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1067 errmsg("invalid input syntax for type json"),
1068 errdetail("Expected string, but found \"%s\".",
1070 report_json_context(lex)));
1072 case JSON_PARSE_ARRAY_START:
1074 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1075 errmsg("invalid input syntax for type json"),
1076 errdetail("Expected array element or \"]\", but found \"%s\".",
1078 report_json_context(lex)));
1080 case JSON_PARSE_ARRAY_NEXT:
1082 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1083 errmsg("invalid input syntax for type json"),
1084 errdetail("Expected \",\" or \"]\", but found \"%s\".",
1086 report_json_context(lex)));
1088 case JSON_PARSE_OBJECT_START:
1090 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1091 errmsg("invalid input syntax for type json"),
1092 errdetail("Expected string or \"}\", but found \"%s\".",
1094 report_json_context(lex)));
1096 case JSON_PARSE_OBJECT_LABEL:
1098 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1099 errmsg("invalid input syntax for type json"),
1100 errdetail("Expected \":\", but found \"%s\".",
1102 report_json_context(lex)));
1104 case JSON_PARSE_OBJECT_NEXT:
1106 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1107 errmsg("invalid input syntax for type json"),
1108 errdetail("Expected \",\" or \"}\", but found \"%s\".",
1110 report_json_context(lex)));
1112 case JSON_PARSE_OBJECT_COMMA:
1114 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1115 errmsg("invalid input syntax for type json"),
1116 errdetail("Expected string, but found \"%s\".",
1118 report_json_context(lex)));
1121 elog(ERROR, "unexpected json parse state: %d", ctx);
1127 * Report an invalid input token.
1129 * lex->token_start and lex->token_terminator must identify the token.
1132 report_invalid_token(JsonLexContext *lex)
1137 /* Separate out the offending token. */
1138 toklen = lex->token_terminator - lex->token_start;
1139 token = palloc(toklen + 1);
1140 memcpy(token, lex->token_start, toklen);
1141 token[toklen] = '\0';
1144 (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1145 errmsg("invalid input syntax for type json"),
1146 errdetail("Token \"%s\" is invalid.", token),
1147 report_json_context(lex)));
1151 * Report a CONTEXT line for bogus JSON input.
1153 * lex->token_terminator must be set to identify the spot where we detected
1154 * the error. Note that lex->token_start might be NULL, in case we recognized
1157 * The return value isn't meaningful, but we make it non-void so that this
1158 * can be invoked inside ereport().
1161 report_json_context(JsonLexContext *lex)
1163 const char *context_start;
1164 const char *context_end;
1165 const char *line_start;
1172 /* Choose boundaries for the part of the input we will display */
1173 context_start = lex->input;
1174 context_end = lex->token_terminator;
1175 line_start = context_start;
1179 /* Always advance over newlines */
1180 if (context_start < context_end && *context_start == '\n')
1183 line_start = context_start;
1187 /* Otherwise, done as soon as we are close enough to context_end */
1188 if (context_end - context_start < 50)
1190 /* Advance to next multibyte character */
1191 if (IS_HIGHBIT_SET(*context_start))
1192 context_start += pg_mblen(context_start);
1198 * We add "..." to indicate that the excerpt doesn't start at the
1199 * beginning of the line ... but if we're within 3 characters of the
1200 * beginning of the line, we might as well just show the whole line.
1202 if (context_start - line_start <= 3)
1203 context_start = line_start;
1205 /* Get a null-terminated copy of the data to present */
1206 ctxtlen = context_end - context_start;
1207 ctxt = palloc(ctxtlen + 1);
1208 memcpy(ctxt, context_start, ctxtlen);
1209 ctxt[ctxtlen] = '\0';
1212 * Show the context, prefixing "..." if not starting at start of line, and
1213 * suffixing "..." if not ending at end of line.
1215 prefix = (context_start > line_start) ? "..." : "";
1216 suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : "";
1218 return errcontext("JSON data, line %d: %s%s%s",
1219 line_number, prefix, ctxt, suffix);
1223 * Extract a single, possibly multi-byte char from the input string.
1226 extract_mb_char(char *s)
1232 res = palloc(len + 1);
1233 memcpy(res, s, len);
1240 * Determine how we want to print values of a given type in datum_to_json.
1242 * Given the datatype OID, return its JsonTypeCategory, as well as the type's
1243 * output function OID. If the returned category is JSONTYPE_CAST, we
1244 * return the OID of the type->JSON cast function instead.
1247 json_categorize_type(Oid typoid,
1248 JsonTypeCategory *tcategory,
1253 /* Look through any domain */
1254 typoid = getBaseType(typoid);
1256 /* We'll usually need to return the type output function */
1257 getTypeOutputInfo(typoid, outfuncoid, &typisvarlena);
1259 /* Check for known types */
1263 *tcategory = JSONTYPE_BOOL;
1272 *tcategory = JSONTYPE_NUMERIC;
1276 *tcategory = JSONTYPE_TIMESTAMP;
1279 case TIMESTAMPTZOID:
1280 *tcategory = JSONTYPE_TIMESTAMPTZ;
1285 *tcategory = JSONTYPE_JSON;
1289 /* Check for arrays and composites */
1290 if (OidIsValid(get_element_type(typoid)))
1291 *tcategory = JSONTYPE_ARRAY;
1292 else if (type_is_rowtype(typoid))
1293 *tcategory = JSONTYPE_COMPOSITE;
1296 /* It's probably the general case ... */
1297 *tcategory = JSONTYPE_OTHER;
1298 /* but let's look for a cast to json, if it's not built-in */
1299 if (typoid >= FirstNormalObjectId)
1303 tuple = SearchSysCache2(CASTSOURCETARGET,
1304 ObjectIdGetDatum(typoid),
1305 ObjectIdGetDatum(JSONOID));
1306 if (HeapTupleIsValid(tuple))
1308 Form_pg_cast castForm = (Form_pg_cast) GETSTRUCT(tuple);
1310 if (castForm->castmethod == COERCION_METHOD_FUNCTION)
1312 *tcategory = JSONTYPE_CAST;
1313 *outfuncoid = castForm->castfunc;
1316 ReleaseSysCache(tuple);
1325 * Turn a Datum into JSON text, appending the string to "result".
1327 * tcategory and outfuncoid are from a previous call to json_categorize_type,
1328 * except that if is_null is true then they can be invalid.
1330 * If key_scalar is true, the value is being printed as a key, so insist
1331 * it's of an acceptable type, and force it to be quoted.
1334 datum_to_json(Datum val, bool is_null, StringInfo result,
1335 JsonTypeCategory tcategory, Oid outfuncoid,
1341 JsonLexContext dummy_lex;
1345 appendStringInfoString(result, "null");
1350 (tcategory == JSONTYPE_ARRAY ||
1351 tcategory == JSONTYPE_COMPOSITE ||
1352 tcategory == JSONTYPE_JSON ||
1353 tcategory == JSONTYPE_CAST))
1355 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1356 errmsg("key value must be scalar, not array, composite or json")));
1360 case JSONTYPE_ARRAY:
1361 array_to_json_internal(val, result, false);
1363 case JSONTYPE_COMPOSITE:
1364 composite_to_json(val, result, false);
1367 outputstr = DatumGetBool(val) ? "true" : "false";
1369 escape_json(result, outputstr);
1371 appendStringInfoString(result, outputstr);
1373 case JSONTYPE_NUMERIC:
1374 outputstr = OidOutputFunctionCall(outfuncoid, val);
1377 /* always quote keys */
1378 escape_json(result, outputstr);
1383 * Don't call escape_json for a non-key if it's a valid JSON
1386 dummy_lex.input = *outputstr == '-' ? outputstr + 1 : outputstr;
1387 dummy_lex.input_length = strlen(dummy_lex.input);
1388 json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error);
1390 appendStringInfoString(result, outputstr);
1392 escape_json(result, outputstr);
1396 case JSONTYPE_TIMESTAMP:
1398 * The timestamp format used here provides for quoting the string,
1399 * so no escaping is required.
1401 jsontext = DatumGetTextP(
1402 DirectFunctionCall2(timestamp_to_char, val,
1403 CStringGetTextDatum(TS_ISO8601_FMT)));
1404 outputstr = text_to_cstring(jsontext);
1405 appendStringInfoString(result, outputstr);
1409 case JSONTYPE_TIMESTAMPTZ:
1410 /* same comment as for timestamp above */
1411 jsontext = DatumGetTextP(
1412 DirectFunctionCall2(timestamptz_to_char, val,
1413 CStringGetTextDatum(TSTZ_ISO8601_FMT)));
1414 outputstr = text_to_cstring(jsontext);
1415 appendStringInfoString(result, outputstr);
1420 /* JSON and JSONB output will already be escaped */
1421 outputstr = OidOutputFunctionCall(outfuncoid, val);
1422 appendStringInfoString(result, outputstr);
1426 /* outfuncoid refers to a cast function, not an output function */
1427 jsontext = DatumGetTextP(OidFunctionCall1(outfuncoid, val));
1428 outputstr = text_to_cstring(jsontext);
1429 appendStringInfoString(result, outputstr);
1434 outputstr = OidOutputFunctionCall(outfuncoid, val);
1435 if (key_scalar && *outputstr == '\0')
1437 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1438 errmsg("key value must not be empty")));
1439 escape_json(result, outputstr);
1446 * Process a single dimension of an array.
1447 * If it's the innermost dimension, output the values, otherwise call
1448 * ourselves recursively to process the next dimension.
1451 array_dim_to_json(StringInfo result, int dim, int ndims, int *dims, Datum *vals,
1452 bool *nulls, int *valcount, JsonTypeCategory tcategory,
1453 Oid outfuncoid, bool use_line_feeds)
1458 Assert(dim < ndims);
1460 sep = use_line_feeds ? ",\n " : ",";
1462 appendStringInfoChar(result, '[');
1464 for (i = 1; i <= dims[dim]; i++)
1467 appendStringInfoString(result, sep);
1469 if (dim + 1 == ndims)
1471 datum_to_json(vals[*valcount], nulls[*valcount], result, tcategory,
1478 * Do we want line feeds on inner dimensions of arrays? For now
1481 array_dim_to_json(result, dim + 1, ndims, dims, vals, nulls,
1482 valcount, tcategory, outfuncoid, false);
1486 appendStringInfoChar(result, ']');
1490 * Turn an array into JSON.
1493 array_to_json_internal(Datum array, StringInfo result, bool use_line_feeds)
1495 ArrayType *v = DatumGetArrayTypeP(array);
1496 Oid element_type = ARR_ELEMTYPE(v);
1506 JsonTypeCategory tcategory;
1511 nitems = ArrayGetNItems(ndim, dim);
1515 appendStringInfoString(result, "[]");
1519 get_typlenbyvalalign(element_type,
1520 &typlen, &typbyval, &typalign);
1522 json_categorize_type(element_type,
1523 &tcategory, &outfuncoid);
1525 deconstruct_array(v, element_type, typlen, typbyval,
1526 typalign, &elements, &nulls,
1529 array_dim_to_json(result, 0, ndim, dim, elements, nulls, &count, tcategory,
1530 outfuncoid, use_line_feeds);
1537 * Turn a composite / record into JSON.
1540 composite_to_json(Datum composite, StringInfo result, bool use_line_feeds)
1546 HeapTupleData tmptup,
1549 bool needsep = false;
1552 sep = use_line_feeds ? ",\n " : ",";
1554 td = DatumGetHeapTupleHeader(composite);
1556 /* Extract rowtype info and find a tupdesc */
1557 tupType = HeapTupleHeaderGetTypeId(td);
1558 tupTypmod = HeapTupleHeaderGetTypMod(td);
1559 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
1561 /* Build a temporary HeapTuple control structure */
1562 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
1566 appendStringInfoChar(result, '{');
1568 for (i = 0; i < tupdesc->natts; i++)
1573 JsonTypeCategory tcategory;
1576 if (tupdesc->attrs[i]->attisdropped)
1580 appendStringInfoString(result, sep);
1583 attname = NameStr(tupdesc->attrs[i]->attname);
1584 escape_json(result, attname);
1585 appendStringInfoChar(result, ':');
1587 val = heap_getattr(tuple, i + 1, tupdesc, &isnull);
1591 tcategory = JSONTYPE_NULL;
1592 outfuncoid = InvalidOid;
1595 json_categorize_type(tupdesc->attrs[i]->atttypid,
1596 &tcategory, &outfuncoid);
1598 datum_to_json(val, isnull, result, tcategory, outfuncoid, false);
1601 appendStringInfoChar(result, '}');
1602 ReleaseTupleDesc(tupdesc);
1606 * Append JSON text for "val" to "result".
1608 * This is just a thin wrapper around datum_to_json. If the same type will be
1609 * printed many times, avoid using this; better to do the json_categorize_type
1610 * lookups only once.
1613 add_json(Datum val, bool is_null, StringInfo result,
1614 Oid val_type, bool key_scalar)
1616 JsonTypeCategory tcategory;
1619 if (val_type == InvalidOid)
1621 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1622 errmsg("could not determine input data type")));
1626 tcategory = JSONTYPE_NULL;
1627 outfuncoid = InvalidOid;
1630 json_categorize_type(val_type,
1631 &tcategory, &outfuncoid);
1633 datum_to_json(val, is_null, result, tcategory, outfuncoid, key_scalar);
1637 * SQL function array_to_json(row)
1640 array_to_json(PG_FUNCTION_ARGS)
1642 Datum array = PG_GETARG_DATUM(0);
1645 result = makeStringInfo();
1647 array_to_json_internal(array, result, false);
1649 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1653 * SQL function array_to_json(row, prettybool)
1656 array_to_json_pretty(PG_FUNCTION_ARGS)
1658 Datum array = PG_GETARG_DATUM(0);
1659 bool use_line_feeds = PG_GETARG_BOOL(1);
1662 result = makeStringInfo();
1664 array_to_json_internal(array, result, use_line_feeds);
1666 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1670 * SQL function row_to_json(row)
1673 row_to_json(PG_FUNCTION_ARGS)
1675 Datum array = PG_GETARG_DATUM(0);
1678 result = makeStringInfo();
1680 composite_to_json(array, result, false);
1682 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1686 * SQL function row_to_json(row, prettybool)
1689 row_to_json_pretty(PG_FUNCTION_ARGS)
1691 Datum array = PG_GETARG_DATUM(0);
1692 bool use_line_feeds = PG_GETARG_BOOL(1);
1695 result = makeStringInfo();
1697 composite_to_json(array, result, use_line_feeds);
1699 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1703 * SQL function to_json(anyvalue)
1706 to_json(PG_FUNCTION_ARGS)
1708 Datum val = PG_GETARG_DATUM(0);
1709 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 0);
1711 JsonTypeCategory tcategory;
1714 if (val_type == InvalidOid)
1716 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1717 errmsg("could not determine input data type")));
1719 json_categorize_type(val_type,
1720 &tcategory, &outfuncoid);
1722 result = makeStringInfo();
1724 datum_to_json(val, false, result, tcategory, outfuncoid, false);
1726 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
1730 * json_agg transition function
1733 json_agg_transfn(PG_FUNCTION_ARGS)
1735 Oid val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1736 MemoryContext aggcontext,
1740 JsonTypeCategory tcategory;
1743 if (val_type == InvalidOid)
1745 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1746 errmsg("could not determine input data type")));
1748 if (!AggCheckCallContext(fcinfo, &aggcontext))
1750 /* cannot be called directly because of internal-type argument */
1751 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1754 if (PG_ARGISNULL(0))
1757 * Make this StringInfo in a context where it will persist for the
1758 * duration of the aggregate call. MemoryContextSwitchTo is only
1759 * needed the first time, as the StringInfo routines make sure they
1760 * use the right context to enlarge the object if necessary.
1762 oldcontext = MemoryContextSwitchTo(aggcontext);
1763 state = makeStringInfo();
1764 MemoryContextSwitchTo(oldcontext);
1766 appendStringInfoChar(state, '[');
1770 state = (StringInfo) PG_GETARG_POINTER(0);
1771 appendStringInfoString(state, ", ");
1774 /* fast path for NULLs */
1775 if (PG_ARGISNULL(1))
1777 datum_to_json((Datum) 0, true, state, JSONTYPE_NULL, InvalidOid, false);
1778 PG_RETURN_POINTER(state);
1781 val = PG_GETARG_DATUM(1);
1783 /* XXX we do this every time?? */
1784 json_categorize_type(val_type,
1785 &tcategory, &outfuncoid);
1787 /* add some whitespace if structured type and not first item */
1788 if (!PG_ARGISNULL(0) &&
1789 (tcategory == JSONTYPE_ARRAY || tcategory == JSONTYPE_COMPOSITE))
1791 appendStringInfoString(state, "\n ");
1794 datum_to_json(val, false, state, tcategory, outfuncoid, false);
1797 * The transition type for array_agg() is declared to be "internal", which
1798 * is a pass-by-value type the same size as a pointer. So we can safely
1799 * pass the ArrayBuildState pointer through nodeAgg.c's machinations.
1801 PG_RETURN_POINTER(state);
1805 * json_agg final function
1808 json_agg_finalfn(PG_FUNCTION_ARGS)
1812 /* cannot be called directly because of internal-type argument */
1813 Assert(AggCheckCallContext(fcinfo, NULL));
1815 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1820 appendStringInfoChar(state, ']');
1822 PG_RETURN_TEXT_P(cstring_to_text_with_len(state->data, state->len));
1826 * json_object_agg transition function.
1828 * aggregate two input columns as a single json value.
1831 json_object_agg_transfn(PG_FUNCTION_ARGS)
1834 MemoryContext aggcontext,
1839 if (!AggCheckCallContext(fcinfo, &aggcontext))
1841 /* cannot be called directly because of internal-type argument */
1842 elog(ERROR, "json_agg_transfn called in non-aggregate context");
1845 if (PG_ARGISNULL(0))
1848 * Make this StringInfo in a context where it will persist for the
1849 * duration off the aggregate call. It's only needed for this initial
1850 * piece, as the StringInfo routines make sure they use the right
1851 * context to enlarge the object if necessary.
1853 oldcontext = MemoryContextSwitchTo(aggcontext);
1854 state = makeStringInfo();
1855 MemoryContextSwitchTo(oldcontext);
1857 appendStringInfoString(state, "{ ");
1861 state = (StringInfo) PG_GETARG_POINTER(0);
1862 appendStringInfoString(state, ", ");
1865 if (PG_ARGISNULL(1))
1867 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1868 errmsg("field name must not be null")));
1871 val_type = get_fn_expr_argtype(fcinfo->flinfo, 1);
1874 * turn a constant (more or less literal) value that's of unknown type
1875 * into text. Unknowns come in as a cstring pointer.
1877 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, 1))
1880 arg = CStringGetTextDatum(PG_GETARG_POINTER(1));
1884 arg = PG_GETARG_DATUM(1);
1887 if (val_type == InvalidOid || val_type == UNKNOWNOID)
1889 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1890 errmsg("arg 1: could not determine data type")));
1892 add_json(arg, false, state, val_type, true);
1894 appendStringInfoString(state, " : ");
1896 val_type = get_fn_expr_argtype(fcinfo->flinfo, 2);
1897 /* see comments above */
1898 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, 2))
1901 if (PG_ARGISNULL(2))
1904 arg = CStringGetTextDatum(PG_GETARG_POINTER(2));
1908 arg = PG_GETARG_DATUM(2);
1911 if (val_type == InvalidOid || val_type == UNKNOWNOID)
1913 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1914 errmsg("arg 2: could not determine data type")));
1916 add_json(arg, PG_ARGISNULL(2), state, val_type, false);
1918 PG_RETURN_POINTER(state);
1922 * json_object_agg final function.
1926 json_object_agg_finalfn(PG_FUNCTION_ARGS)
1930 /* cannot be called directly because of internal-type argument */
1931 Assert(AggCheckCallContext(fcinfo, NULL));
1933 state = PG_ARGISNULL(0) ? NULL : (StringInfo) PG_GETARG_POINTER(0);
1936 PG_RETURN_TEXT_P(cstring_to_text("{}"));
1938 appendStringInfoString(state, " }");
1940 PG_RETURN_TEXT_P(cstring_to_text_with_len(state->data, state->len));
1944 * SQL function json_build_object(variadic "any")
1947 json_build_object(PG_FUNCTION_ARGS)
1949 int nargs = PG_NARGS();
1959 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1960 errmsg("invalid number or arguments: object must be matched key value pairs")));
1962 result = makeStringInfo();
1964 appendStringInfoChar(result, '{');
1966 for (i = 0; i < nargs; i += 2)
1971 if (PG_ARGISNULL(i))
1973 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1974 errmsg("arg %d: key cannot be null", i + 1)));
1975 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
1978 * turn a constant (more or less literal) value that's of unknown type
1979 * into text. Unknowns come in as a cstring pointer.
1981 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i))
1984 if (PG_ARGISNULL(i))
1987 arg = CStringGetTextDatum(PG_GETARG_POINTER(i));
1991 arg = PG_GETARG_DATUM(i);
1993 if (val_type == InvalidOid || val_type == UNKNOWNOID)
1995 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1996 errmsg("arg %d: could not determine data type", i + 1)));
1997 appendStringInfoString(result, sep);
1999 add_json(arg, false, result, val_type, true);
2001 appendStringInfoString(result, " : ");
2005 val_type = get_fn_expr_argtype(fcinfo->flinfo, i + 1);
2006 /* see comments above */
2007 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i + 1))
2010 if (PG_ARGISNULL(i + 1))
2013 arg = CStringGetTextDatum(PG_GETARG_POINTER(i + 1));
2017 arg = PG_GETARG_DATUM(i + 1);
2019 if (val_type == InvalidOid || val_type == UNKNOWNOID)
2021 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2022 errmsg("arg %d: could not determine data type", i + 2)));
2023 add_json(arg, PG_ARGISNULL(i + 1), result, val_type, false);
2026 appendStringInfoChar(result, '}');
2028 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2033 * degenerate case of json_build_object where it gets 0 arguments.
2036 json_build_object_noargs(PG_FUNCTION_ARGS)
2038 PG_RETURN_TEXT_P(cstring_to_text_with_len("{}", 2));
2042 * SQL function json_build_array(variadic "any")
2045 json_build_array(PG_FUNCTION_ARGS)
2047 int nargs = PG_NARGS();
2055 result = makeStringInfo();
2057 appendStringInfoChar(result, '[');
2059 for (i = 0; i < nargs; i++)
2061 val_type = get_fn_expr_argtype(fcinfo->flinfo, i);
2062 arg = PG_GETARG_DATUM(i + 1);
2063 /* see comments in json_build_object above */
2064 if (val_type == UNKNOWNOID && get_fn_expr_arg_stable(fcinfo->flinfo, i))
2067 if (PG_ARGISNULL(i))
2070 arg = CStringGetTextDatum(PG_GETARG_POINTER(i));
2074 arg = PG_GETARG_DATUM(i);
2076 if (val_type == InvalidOid || val_type == UNKNOWNOID)
2078 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2079 errmsg("arg %d: could not determine data type", i + 1)));
2080 appendStringInfoString(result, sep);
2082 add_json(arg, PG_ARGISNULL(i), result, val_type, false);
2084 appendStringInfoChar(result, ']');
2086 PG_RETURN_TEXT_P(cstring_to_text_with_len(result->data, result->len));
2091 * degenerate case of json_build_array where it gets 0 arguments.
2094 json_build_array_noargs(PG_FUNCTION_ARGS)
2096 PG_RETURN_TEXT_P(cstring_to_text_with_len("[]", 2));
2100 * SQL function json_object(text[])
2102 * take a one or two dimensional array of text as name vale pairs
2103 * for a json object.
2107 json_object(PG_FUNCTION_ARGS)
2109 ArrayType *in_array = PG_GETARG_ARRAYTYPE_P(0);
2110 int ndims = ARR_NDIM(in_array);
2111 StringInfoData result;
2123 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2127 if ((ARR_DIMS(in_array)[0]) % 2)
2129 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2130 errmsg("array must have even number of elements")));
2134 if ((ARR_DIMS(in_array)[1]) != 2)
2136 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2137 errmsg("array must have two columns")));
2142 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2143 errmsg("wrong number of array subscripts")));
2146 deconstruct_array(in_array,
2147 TEXTOID, -1, false, 'i',
2148 &in_datums, &in_nulls, &in_count);
2150 count = in_count / 2;
2152 initStringInfo(&result);
2154 appendStringInfoChar(&result, '{');
2156 for (i = 0; i < count; ++i)
2158 if (in_nulls[i * 2])
2160 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2161 errmsg("null value not allowed for object key")));
2163 v = TextDatumGetCString(in_datums[i * 2]);
2166 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2167 errmsg("empty value not allowed for object key")));
2169 appendStringInfoString(&result, ", ");
2170 escape_json(&result, v);
2171 appendStringInfoString(&result, " : ");
2173 if (in_nulls[i * 2 + 1])
2174 appendStringInfoString(&result, "null");
2177 v = TextDatumGetCString(in_datums[i * 2 + 1]);
2178 escape_json(&result, v);
2183 appendStringInfoChar(&result, '}');
2188 rval = cstring_to_text_with_len(result.data, result.len);
2191 PG_RETURN_TEXT_P(rval);
2196 * SQL function json_object(text[], text[])
2198 * take separate name and value arrays of text to construct a json object
2202 json_object_two_arg(PG_FUNCTION_ARGS)
2204 ArrayType *key_array = PG_GETARG_ARRAYTYPE_P(0);
2205 ArrayType *val_array = PG_GETARG_ARRAYTYPE_P(1);
2206 int nkdims = ARR_NDIM(key_array);
2207 int nvdims = ARR_NDIM(val_array);
2208 StringInfoData result;
2219 if (nkdims > 1 || nkdims != nvdims)
2221 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2222 errmsg("wrong number of array subscripts")));
2225 PG_RETURN_DATUM(CStringGetTextDatum("{}"));
2227 deconstruct_array(key_array,
2228 TEXTOID, -1, false, 'i',
2229 &key_datums, &key_nulls, &key_count);
2231 deconstruct_array(val_array,
2232 TEXTOID, -1, false, 'i',
2233 &val_datums, &val_nulls, &val_count);
2235 if (key_count != val_count)
2237 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2238 errmsg("mismatched array dimensions")));
2240 initStringInfo(&result);
2242 appendStringInfoChar(&result, '{');
2244 for (i = 0; i < key_count; ++i)
2248 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2249 errmsg("null value not allowed for object key")));
2251 v = TextDatumGetCString(key_datums[i]);
2254 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2255 errmsg("empty value not allowed for object key")));
2257 appendStringInfoString(&result, ", ");
2258 escape_json(&result, v);
2259 appendStringInfoString(&result, " : ");
2262 appendStringInfoString(&result, "null");
2265 v = TextDatumGetCString(val_datums[i]);
2266 escape_json(&result, v);
2271 appendStringInfoChar(&result, '}');
2278 rval = cstring_to_text_with_len(result.data, result.len);
2281 PG_RETURN_TEXT_P(rval);
2287 * Produce a JSON string literal, properly escaping characters in the text.
2290 escape_json(StringInfo buf, const char *str)
2294 appendStringInfoCharMacro(buf, '\"');
2295 for (p = str; *p; p++)
2300 appendStringInfoString(buf, "\\b");
2303 appendStringInfoString(buf, "\\f");
2306 appendStringInfoString(buf, "\\n");
2309 appendStringInfoString(buf, "\\r");
2312 appendStringInfoString(buf, "\\t");
2315 appendStringInfoString(buf, "\\\"");
2319 * Unicode escapes are passed through as is. There is no
2320 * requirement that they denote a valid character in the
2321 * server encoding - indeed that is a big part of their
2324 * All we require is that they consist of \uXXXX where
2325 * the Xs are hexadecimal digits. It is the responsibility
2326 * of the caller of, say, to_json() to make sure that the
2327 * unicode escape is valid.
2329 * In the case of a jsonb string value being escaped, the
2330 * only unicode escape that should be present is \u0000,
2331 * all the other unicode escapes will have been resolved.
2333 if (p[1] == 'u' && isxdigit(p[2]) && isxdigit(p[3])
2334 && isxdigit(p[4]) && isxdigit(p[5]))
2335 appendStringInfoCharMacro(buf, *p);
2337 appendStringInfoString(buf, "\\\\");
2340 if ((unsigned char) *p < ' ')
2341 appendStringInfo(buf, "\\u%04x", (int) *p);
2343 appendStringInfoCharMacro(buf, *p);
2347 appendStringInfoCharMacro(buf, '\"');
2351 * SQL function json_typeof(json) -> text
2353 * Returns the type of the outermost JSON value as TEXT. Possible types are
2354 * "object", "array", "string", "number", "boolean", and "null".
2356 * Performs a single call to json_lex() to get the first token of the supplied
2357 * value. This initial token uniquely determines the value's type. As our
2358 * input must already have been validated by json_in() or json_recv(), the
2359 * initial token should never be JSON_TOKEN_OBJECT_END, JSON_TOKEN_ARRAY_END,
2360 * JSON_TOKEN_COLON, JSON_TOKEN_COMMA, or JSON_TOKEN_END.
2363 json_typeof(PG_FUNCTION_ARGS)
2367 JsonLexContext *lex;
2371 json = PG_GETARG_TEXT_P(0);
2372 lex = makeJsonLexContext(json, false);
2374 /* Lex exactly one token from the input and check its type. */
2376 tok = lex_peek(lex);
2379 case JSON_TOKEN_OBJECT_START:
2382 case JSON_TOKEN_ARRAY_START:
2385 case JSON_TOKEN_STRING:
2388 case JSON_TOKEN_NUMBER:
2391 case JSON_TOKEN_TRUE:
2392 case JSON_TOKEN_FALSE:
2395 case JSON_TOKEN_NULL:
2399 elog(ERROR, "unexpected json token: %d", tok);
2402 PG_RETURN_TEXT_P(cstring_to_text(type));