node-jq icon indicating copy to clipboard operation
node-jq copied to clipboard

ZodError when processing objects with `undefined` values

Open nahoj opened this issue 8 months ago • 3 comments

Description

When passing an object with undefined properties to jq.run(), node-jq throws a ZodError instead of handling the case gracefully. This occurs with any jq filter.

Environment

  • TypeScript
  • node-jq version: 6.0.1
  • Node.js version: v22.15.1
  • Platform: Linux

Minimal Reproduction

import jq from "node-jq";

async function reproduceZodError() {
  const data = { x: undefined, y: "hello" };
  
  try {
    const result = await jq.run('.', data, { input: "json", output: "json" });
    console.log("Success:", result);
  } catch (error) {
    console.log("ZodError occurred:", error.message);
  }
}

reproduceZodError();

Expected Behavior

I suppose there are several behaviors that could be considered valid:

  1. Treating undefined as null
  2. Filtering out undefined properties like JSON.stringify()
  3. Specific error message

Actual Behavior

Throws a ZodError with validation errors:

ZodError: [
  {
    "code": "invalid_union",
    "unionErrors": [
      // ... lots of nested errors
    ],
    "path": ["json", "x"],
    "message": "Invalid input"
  }
]

Workaround

Remove undefined values before processing:

function removeUndefined(obj) {
  return JSON.parse(JSON.stringify(obj));
}

const cleanData = removeUndefined(originalData);
const result = await jq.run('.', cleanData, { input: "json", output: "json" });

PS: Part of this was written by Claude Code; it also helped identify the bug.

nahoj avatar Jun 17 '25 22:06 nahoj

Hi. Thanks for the issue Since JSON doesn't have undefined as a value. Once we cross into jq, is treated like JSON and put back into JavaScript. I like your idea of treating like stringify, but wouldn't like to do it for all data.

Feel free to push a PR with a fix, I'm more torn into the idea of behaving as JS, rathen than throwing/erroing here

davesnx avatar Jun 18 '25 10:06 davesnx

Thank you for your reply. What do you mean by this?

but wouldn't like to do it for all data.

nahoj avatar Jun 18 '25 17:06 nahoj

I meant to avoid iterating for all fields and removing undefineds or other transformations. Maybe the JSON.strinfigy/parse inside node-jq is a good idea?

davesnx avatar Jun 19 '25 10:06 davesnx