Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - Problem when parsing JSON string inside another JSON on Windows

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.

like image 957
Alexandre Thebaldi Avatar asked Mar 15 '26 18:03

Alexandre Thebaldi


2 Answers

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 \".

like image 158
PLASMA chicken Avatar answered Mar 17 '26 07:03

PLASMA chicken


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));
like image 43
Shiny Avatar answered Mar 17 '26 07:03

Shiny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!