{"record":{"id":"84b545ffaf3c1f48","repo":"dbt-labs/dbt-core","slug":"failed-to-convert-value-to-json-err","errorCode":null,"errorMessage":"Failed to convert value to JSON: {err}","messagePattern":"Failed to convert value to JSON: (.+?)","errorType":"exception","errorClass":"InvalidOperation","httpStatus":null,"severity":"error","filePath":"crates/dbt-jinja-utils/src/functions/base.rs","lineNumber":477,"sourceCode":"        Ok(mut json_value) => {\n            if sort_keys && let Some(obj) = json_value.as_object_mut() {\n                // Sort the keys using BTreeMap\n                let sorted: serde_json::Map<String, serde_json::Value> = obj\n                    .iter()\n                    .collect::<BTreeMap<_, _>>()\n                    .into_iter()\n                    .map(|(k, v)| (k.clone(), v.clone()))\n                    .collect();\n                json_value = serde_json::Value::Object(sorted);\n            }\n            // Use Python-style formatting (space after colon)\n            let json_str =\n                to_json_string_python_style(&json_value).unwrap_or_else(|_| \"{}\".to_string());\n            Ok(Value::from_safe_string(json_str))\n        }\n        Err(err) => match default {\n            Some(default_value) => Ok(default_value.clone()),\n            None => Err(Error::new(\n                ErrorKind::InvalidOperation,\n                format!(\"Failed to convert value to JSON: {err}\"),\n            )),\n        },\n    }\n}\n\n/// Deserialize a YAML string into a Python object primitive.\n///\n/// ```python\n/// def fromyaml(value: str, default: Any = None) -> Any:\n///     \"\"\"The fromyaml context method can be used to deserialize a yaml string\n///     into a Python object primitive, eg. a `dict` or `list`.\n///\n///     :param value: The yaml string to deserialize\n///     :param default: A default value to return if the `string` argument\n///         cannot be deserialized (optional)\n///","sourceCodeStart":459,"sourceCodeEnd":495,"githubUrl":"https://github.com/dbt-labs/dbt-core/blob/0267ce9170576975b76b64ce856b2e5848e96617/crates/dbt-jinja-utils/src/functions/base.rs#L459-L495","documentation":"The tojson Jinja filter serializes a value to a Python-style JSON string. When the underlying conversion to a serde_json value fails and no default argument was supplied, this InvalidOperation error is raised carrying the serialization error message. With a default provided, the default is returned instead.","triggerScenarios":"{{ value | tojson }} where value is not JSON-serializable (cyclic structure, non-string map keys that can't convert, or an opaque minijinja value), and no default parameter is passed.","commonSituations":"Serializing undefined or exotic objects from context, dumping results of macros that return unsupported types, or templates that relied on implicit coercion.","solutions":["Pass a default: {{ value | tojson(default='{}') }} to fall back on serialization failure.","Ensure the value is plain data (dict/list/scalar) before piping to tojson.","Guard with is defined / is mapping tests before serializing.","If serializing a dbt relation or object, serialize its serializable attributes instead."],"exampleFix":"// before\n{{ config_obj | tojson }}\n// after\n{{ config_obj | tojson(default='{}') }}","handlingStrategy":"fallback","validationCode":"{% if value is defined and (value is mapping or value is sequence or value is string) %}...{% endif %}","typeGuard":null,"tryCatchPattern":"{{ value | tojson(default='{}') }} // graceful fallback inside the filter","preventionTips":["Always pass a default to tojson for user-controlled values.","Only pipe plain data structures into tojson.","Validate context values are defined before serialization."],"tags":["jinja","json","serialization","tojson"],"backgroundTag":"json-marshal-failed","analyzedSha":"0267ce9170576975b76b64ce856b2e5848e96617","analyzedAt":"2026-09-07T21:53:39.732Z","contentChangedAt":"2026-09-07T21:53:39.732Z","schemaVersion":2},"datasetVersion":"2026-09-14T16:17:12.679Z"}