{"record":{"id":"499056875663e620","repo":"prestodb/presto","slug":"invalid-cast-argument-499056","errorCode":"INVALID_CAST_ARGUMENT","errorMessage":"Unexpected token when cast to %s: %s","messagePattern":"Unexpected token when cast to (.+?): (.+?)","errorType":"error_code","errorClass":"JsonCastException","httpStatus":null,"severity":"error","filePath":"presto-main-base/src/main/java/com/facebook/presto/util/JsonUtil.java","lineNumber":702,"sourceCode":"        switch (parser.currentToken()) {\n            case VALUE_NULL:\n                return null;\n            case VALUE_STRING:\n            case FIELD_NAME:\n                return Slices.utf8Slice(parser.getText());\n            case VALUE_NUMBER_FLOAT:\n                // Avoidance of loss of precision does not seem to be possible here because of Jackson implementation.\n                return DoubleOperators.castToVarchar(parser.getDoubleValue());\n            case VALUE_NUMBER_INT:\n                // An alternative is calling getLongValue and then BigintOperators.castToVarchar.\n                // It doesn't work as well because it can result in overflow and underflow exceptions for large integral numbers.\n                return Slices.utf8Slice(parser.getText());\n            case VALUE_TRUE:\n                return BooleanOperators.castToVarchar(true);\n            case VALUE_FALSE:\n                return BooleanOperators.castToVarchar(false);\n            default:\n                throw new JsonCastException(format(\"Unexpected token when cast to %s: %s\", StandardTypes.VARCHAR, parser.getText()));\n        }\n    }\n\n    public static Long currentTokenAsBigint(JsonParser parser)\n            throws IOException\n    {\n        switch (parser.currentToken()) {\n            case VALUE_NULL:\n                return null;\n            case VALUE_STRING:\n            case FIELD_NAME:\n                return VarcharOperators.castToBigint(Slices.utf8Slice(parser.getText()));\n            case VALUE_NUMBER_FLOAT:\n                return DoubleOperators.castToLong(parser.getDoubleValue());\n            case VALUE_NUMBER_INT:\n                return parser.getLongValue();\n            case VALUE_TRUE:\n                return BooleanOperators.castToBigint(true);","sourceCodeStart":684,"sourceCodeEnd":720,"githubUrl":"https://github.com/prestodb/presto/blob/55bb57d202de3b926896fa966c2c4a44c779634e/presto-main-base/src/main/java/com/facebook/presto/util/JsonUtil.java#L684-L720","documentation":"currentTokenAsVarchar converts the current Jackson parser token to a Presto VARCHAR during JSON-to-SQL casting. Only VALUE_STRING, VALUE_NUMBER, VALUE_TRUE and VALUE_FALSE are convertible; any other token (null, START_OBJECT, START_ARRAY, FIELD_NAME, NOT_AVAILABLE, embedded objects) throws JsonCastException (INVALID_CAST_ARGUMENT) naming VARCHAR and the offending token text.","triggerScenarios":"Casting a JSON value that is an object, array, or null to VARCHAR — e.g. CAST(JSON 'null' AS VARCHAR), CAST(JSON '{\"a\":1}' AS VARCHAR), or a JSON path/unnest landing on a non-scalar token.","commonSituations":"Ingesting semi-structured JSON where a field expected to be a string is sometimes an object/array/null; schema drift between producer and consumer; using json_extract with an implicit cast when the path hits a container.","solutions":["Check the JSON value is a scalar (string, number, or boolean) before casting to VARCHAR; handle nulls with json_typeof or JSON_QUERY wrappers.","Coerce objects/arrays with json_format(CAST(col AS JSON)) instead of direct CAST to VARCHAR.","Fix the upstream producer so the field is always a JSON string, or use TRY_CAST to get NULL instead of a query failure."],"exampleFix":"// before\nSELECT CAST(json_extract(j, '$.details') AS VARCHAR) FROM t; -- fails when details is an object\n// after\nSELECT TRY_CAST(json_extract(j, '$.details') AS VARCHAR) FROM t; -- NULL instead of error, or guard with json_typeof","handlingStrategy":"try-catch","validationCode":"SELECT json_typeof(json_extract(j, '$.path'))\nFROM t; -- must be 'string', 'number', or 'boolean' before CAST to VARCHAR","typeGuard":"boolean isVarcharCastable(String jsonValue) {\n    String t = jsonTypeOf(jsonValue); // e.g. via json_typeof\n    return \"string\".equals(t) || \"number\".equals(t) || \"boolean\".equals(t);\n}","tryCatchPattern":"try {\n    v = castJsonToVarchar(j);\n} catch (PrestoException e) {\n    if (e.getErrorCode().getName().equals(\"INVALID_CAST_ARGUMENT\") && e.getMessage().contains(\"varchar\")) {\n        v = jsonFormat(j); // serialize objects/arrays instead\n    } else { throw e; }\n}","preventionTips":["Check json_typeof before casting extracted JSON values.","Use json_format for objects/arrays instead of direct VARCHAR casts.","Prefer TRY_CAST for untrusted semi-structured JSON."],"tags":["json","invalid-cast-argument","cast","presto"],"backgroundTag":"json-cast-invalid-token","analyzedSha":"55bb57d202de3b926896fa966c2c4a44c779634e","analyzedAt":"2026-09-04T12:50:26.162Z","contentChangedAt":"2026-09-04T12:50:26.162Z","schemaVersion":2},"datasetVersion":"2026-09-11T21:17:09.523Z"}