swc-project/swc · error

jsonify: Expr {:?} cannot be converted to json

Error message

jsonify: Expr {:?} cannot be converted to json

What it means

The json_parse optimizer pass (swc_ecma_transforms_optimization::json_parse, swc issue #409) rewrites deeply-nested literal object/array expressions into `JSON.parse("...")` calls. It first checks the expression with calc_literal_cost and then serializes it via the JsonLiteral serde adapter; the adapter only supports literal objects/arrays/strings/numbers/bools/null and single-quasi template literals. If the cost check classifies an expression as literal but the serializer cannot convert it, this unreachable! fires — an internal mismatch between the two functions.

Source

Thrown at crates/swc_ecma_transforms_optimization/src/json_parse.rs:213

                };
                RawValue::from_string(value.into())
                    .unwrap()
                    .serialize(serializer)
            }
            Expr::Lit(Lit::Num(Number { value, .. })) => json_number(*value).serialize(serializer),
            Expr::Lit(Lit::Null(..)) => serializer.serialize_none(),
            Expr::Lit(Lit::Bool(v)) => serializer.serialize_bool(v.value),
            Expr::Tpl(Tpl { quasis, .. }) => {
                let value = match quasis.first() {
                    Some(TplElement {
                        cooked: Some(value),
                        ..
                    }) => wtf8_to_json_string(value),
                    _ => String::new(),
                };
                value.serialize(serializer)
            }
            _ => unreachable!("jsonify: Expr {:?} cannot be converted to json", self.0),
        }
    }
}

#[cfg(test)]
mod tests {
    use swc_ecma_transforms_testing::test;

    use super::*;

    test!(
        ::swc_ecma_parser::Syntax::default(),
        |_| json_parse(0),
        simple_object,
        "let a = {b: 'foo'}"
    );

    test!(

View on GitHub (pinned to 5176682b65)

Solutions

  1. Update swc_core — mismatches between calc_literal_cost and JsonLiteral are bugs that get patched.
  2. Disable the json optimization or raise its cost threshold (json_parse(min_cost) with usize::MAX disables the pass entirely; jsc.optimizer json_parse/jsonify settings control it via config).
  3. If it persists on the latest version, reduce to the offending literal and file an swc issue.

Example fix

// before: pass enabled at default threshold
let pass = swc_ecma_transforms_optimization::json_parse(1024);

// after: disable by making the threshold unreachable
let pass = swc_ecma_transforms_optimization::json_parse(usize::MAX);
// (or set jsc.optimizer json_parse/jsonify off in .swcrc)
Defensive patterns

Strategy: validation

Validate before calling

// Skip jsonification for literals the serializer can't handle
use swc_ecma_ast::Expr; use swc_ecma_visit::{Visit, VisitWith};
struct NonJsonLiteral(bool); impl Visit for NonJsonLiteral {
    fn visit_expr(&mut self, e: &Expr) {
        self.0 |= matches!(e, Expr::Lit(l) if matches!(l, swc_ecma_ast::Lit::Regex(_) | swc_ecma_ast::Lit::BigInt(_)));
        e.visit_children_with(self);
    }
}
// if scan is true, run json_parse with usize::MAX (disabled) or raise min_cost

Type guard

fn json_serializable_literal(e: &Expr) -> bool {
    matches!(e, Expr::Object(_) | Expr::Array(_) | Expr::Lit(Lit::Str(_) | Lit::Num(_) | Lit::Bool(_) | Lit::Null(_)) | Expr::Tpl(_))
}

Prevention

When it happens

Trigger: Running the optimizer with json_parse enabled on a large object/array literal that contains an expression type calc_literal_cost accepts but JsonLiteral rejects (e.g. a regex/bigint literal or an unusual literal form nested deep enough to cross min_cost). Wired in through swc's optimizer/jsonify settings or by including json_parse(min_cost) in a custom chain.

Common situations: Minifier/optimizer configurations enabling jsonify/json_parse on codebases with big constant tables; swc_core upgrades changing one of the two functions but not the other; embedding Optimizer in build tools.

Related errors


AI-assisted analysis of swc-project/swc@5176682b65 (2026-08-17). Data as JSON: /api/errors/cc53fec5167a06b6. Report an issue: GitHub.