aboutsummaryrefslogtreecommitdiff
path: root/src/backend/utils/adt/json.c
diff options
context:
space:
mode:
authorAndrew Dunstan <andrew@dunslane.net>2014-12-01 11:28:45 -0500
committerAndrew Dunstan <andrew@dunslane.net>2014-12-01 11:44:48 -0500
commit55c8807978e86f615623eb7922c114b841f14557 (patch)
tree12b1947890f2545d8f1b8f509ecfe905612d352b /src/backend/utils/adt/json.c
parent5c9a4a866efcc15ec041134538e01f25c2e2bd88 (diff)
downloadpostgresql-55c8807978e86f615623eb7922c114b841f14557.tar.gz
postgresql-55c8807978e86f615623eb7922c114b841f14557.zip
Fix hstore_to_json_loose's detection of valid JSON number values.
We expose a function IsValidJsonNumber that internally calls the lexer for json numbers. That allows us to use the same test everywhere, instead of inventing a broken test for hstore conversions. The new function is also used in datum_to_json, replacing the code that is now moved to the new function. Backpatch to 9.3 where hstore_to_json_loose was introduced.
Diffstat (limited to 'src/backend/utils/adt/json.c')
-rw-r--r--src/backend/utils/adt/json.c40
1 files changed, 33 insertions, 7 deletions
diff --git a/src/backend/utils/adt/json.c b/src/backend/utils/adt/json.c
index 53a011d50b4..0873bb3ce15 100644
--- a/src/backend/utils/adt/json.c
+++ b/src/backend/utils/adt/json.c
@@ -164,6 +164,36 @@ lex_expect(JsonParseContext ctx, JsonLexContext *lex, JsonTokenType token)
(c) == '_' || \
IS_HIGHBIT_SET(c))
+/* utility function to check if a string is a valid JSON number */
+extern bool
+IsValidJsonNumber(const char * str, int len)
+{
+ bool numeric_error;
+ JsonLexContext dummy_lex;
+
+
+ /*
+ * json_lex_number expects a leading '-' to have been eaten already.
+ *
+ * having to cast away the constness of str is ugly, but there's not much
+ * easy alternative.
+ */
+ if (*str == '-')
+ {
+ dummy_lex.input = (char *) str + 1;
+ dummy_lex.input_length = len - 1;
+ }
+ else
+ {
+ dummy_lex.input = (char *) str;
+ dummy_lex.input_length = len;
+ }
+
+ json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error);
+
+ return ! numeric_error;
+}
+
/*
* Input.
*/
@@ -1306,8 +1336,6 @@ datum_to_json(Datum val, bool is_null, StringInfo result,
{
char *outputstr;
text *jsontext;
- bool numeric_error;
- JsonLexContext dummy_lex;
if (is_null)
{
@@ -1332,12 +1360,10 @@ datum_to_json(Datum val, bool is_null, StringInfo result,
case JSONTYPE_NUMERIC:
outputstr = OidOutputFunctionCall(outfuncoid, val);
/*
- * Don't call escape_json here if it's a valid JSON number.
+ * Don't call escape_json for a non-key if it's a valid JSON
+ * number.
*/
- dummy_lex.input = *outputstr == '-' ? outputstr + 1 : outputstr;
- dummy_lex.input_length = strlen(dummy_lex.input);
- json_lex_number(&dummy_lex, dummy_lex.input, &numeric_error);
- if (! numeric_error)
+ if (!key_scalar && IsValidJsonNumber(outputstr, strlen(outputstr)))
appendStringInfoString(result, outputstr);
else
escape_json(result, outputstr);