ZodError when processing objects with `undefined` values
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:
- Treating
undefinedasnull - Filtering out
undefinedproperties likeJSON.stringify() - 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.
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
Thank you for your reply. What do you mean by this?
but wouldn't like to do it for all data.
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?