{"record":{"id":"598145126dbff71f","repo":"karatelabs/karate","slug":"tojson-requires-an-object-argument","errorCode":null,"errorMessage":"toJson() requires an object argument","messagePattern":"toJson\\(\\) requires an object argument","errorType":"validation","errorClass":"RuntimeException","httpStatus":null,"severity":"error","filePath":"karate-core/src/main/java/io/karatelabs/markup/MarkupContext.java","lineNumber":140,"sourceCode":"        return switch (key) {\n            case \"template\" -> getTemplateName();\n            case \"caller\" -> getCallerTemplateName();\n            case \"read\" -> (JavaInvokable) args -> {\n                if (args.length == 0 || args[0] == null) {\n                    throw new RuntimeException(\"read() requires a path argument\");\n                }\n                return read(args[0].toString());\n            };\n            case \"readBytes\" -> (JavaInvokable) args -> {\n                if (args.length == 0 || args[0] == null) {\n                    throw new RuntimeException(\"readBytes() requires a path argument\");\n                }\n                return readBytes(args[0].toString());\n            };\n            case \"toJson\" -> (JavaInvokable) args -> {\n                // null IS a valid JSON-able value (`null`), so only the\n                // missing-arg case errors here.\n                if (args.length == 0) throw new RuntimeException(\"toJson() requires an object argument\");\n                return toJson(args[0]);\n            };\n            case \"fromJson\" -> (JavaInvokable) args -> {\n                if (args.length == 0 || args[0] == null) {\n                    throw new RuntimeException(\"fromJson() requires a JSON string argument\");\n                }\n                return fromJson(args[0].toString());\n            };\n            // context.get(name, default?) for optional fragment params.\n            // Walks the current eval scope (`_` map first, then wrapped\n            // Thymeleaf scope). Returns the bound non-null value if found,\n            // else the default (or null when no default is given).\n            case \"get\" -> (JavaInvokable) args -> {\n                if (args.length == 0 || args[0] == null) {\n                    throw new RuntimeException(\"context.get() requires a name argument\");\n                }\n                String name = args[0].toString();\n                Object defaultValue = args.length > 1 ? args[1] : null;","sourceCodeStart":122,"sourceCodeEnd":158,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-core/src/main/java/io/karatelabs/markup/MarkupContext.java#L122-L158","documentation":"MarkupContext exposes a JS-callable `toJson(value)` that serializes a value to a JSON string. Null is considered a valid JSON-able value (serializes as `null`), so the only case rejected is calling `toJson()` with zero arguments, which throws this RuntimeException.","triggerScenarios":"Calling `context.toJson()` with no arguments in template script — e.g. `th:text=\"${context.toJson()}\"` or building an inline JSON payload without passing the object.","commonSituations":"Dropping the argument while refactoring expressions; dynamic data variable that was removed from the call instead of being null; hand-writing JSON islands in templates and misplacing the argument.","solutions":["Pass the value explicitly, even null: `context.toJson(null)` produces the string 'null'.","If the data variable may be absent, pass a fallback: `context.toJson(data ?: {})`.","Check that the intended model key is actually bound in the render scope.","Remember toJson accepts any object including maps/lists — the error only fires for a missing argument, not a bad type."],"exampleFix":"// before\n<script th:inline=\"text\">var cfg = ${context.toJson()};</script>\n\n// after\n<script th:inline=\"text\">var cfg = ${context.toJson(config)};</script>","handlingStrategy":"validation","validationCode":"function safeToJson(ctx, v) {\n  return ctx.toJson(v === undefined ? null : v);\n}","typeGuard":"function isProvided(v) { return typeof v !== 'undefined'; }\n// usage: if (!isProvided(v)) v = null; then context.toJson(v)","tryCatchPattern":"try {\n  var json = context.toJson(v);\n} catch (e) {\n  if (e.message === 'toJson() requires an object argument') {\n    json = 'null';\n  } else { throw e; }\n}","preventionTips":["toJson(null) is valid — pass null explicitly rather than omitting the argument","Default missing data with `data ?: {}` before serializing","Confirm the model variable exists before inlining JSON in scripts","Remember only the zero-argument case errors; any type is accepted"],"tags":["markup","javascript-binding","json","missing-argument"],"backgroundTag":"missing-required-argument","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-16T19:17:19.609Z"}