My nodejs application receives an argument that contains a JSON string as value. For example:
node index.js --json-items='[{"a": 10, "b": 20}]'
And inside index.js:
const { jsonItems } = argv
const items = JSON.parse(jsonItems)
// Works...
So I made it automatic via package.json scripts (JSON scaped):
{
"scripts": {
"dev": "node index.js --json-items='[{\"a\": 10, \"b\": 20}]'"
}
}
On my MacOS it still working because the arg is scaped correctly:
const { jsonItems } = argv
// (string) '[{"a": 10, "b": 20}]'
But on a Windows it doesn't because double quotes are removed:
const { jsonItems } = argv
// (string) '[{a: 10, b: 20}]'
// JSON.parse() -> Uncaught SyntaxError: Unexpected token...
How to resolve this?
Or just how to convert before JSON.parse():
'[{a: 10, b: 20}]' -> '[{"a": 10, "b": 20}]'
I'm using yargs package to get the arguments.
This seems to be an issue with how Windows and NPM and then finally Node handle the quotes.
"dev": "node index.js --json-items=\"[{\\\"a\\\": 10, \\\"b\\\": 20}]\""
You first need to escape it once for the json, and then you need to escape it again for windows/node. Also ' does not seem to work too good either so I recommend \".
You can use this regex to wrap double quotes around each Object Key, so you could just us this before the JSON.parse()
let validJSON = '[{a: 10, b: 20}]'.replace(/([{,])(\s*)([A-Za-z0-9_\-]+?)\s*:/g, '$1"$3":')
console.log(validJSON);
console.log(JSON.parse(validJSON));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With