javascript - NodeJS - 在 Windows 上解析另一个 JSON 中的 JSON 字符串时出现问题

标签 javascript node.js json windows

我的 nodejs 应用程序收到一个包含 JSON 字符串作为值的参数。例如:

node index.js --json-items='[{"a": 10, "b": 20}]'

index.js 中:

const { jsonItems } = argv
const items = JSON.parse(jsonItems)
// Works...

所以我通过 package.json 脚本(JSON scaped)让它自动运行:

{
  "scripts": {
    "dev": "node index.js --json-items='[{\"a\": 10, \"b\": 20}]'"
   }
}

在我的 MacOS 上它仍然有效,因为 arg 被正确转义了:

const { jsonItems } = argv
// (string) '[{"a": 10, "b": 20}]'

但在 Windows 上它不会,因为双引号被删除了:

const { jsonItems } = argv
// (string) '[{a: 10, b: 20}]'
// JSON.parse() -> Uncaught SyntaxError: Unexpected token...

如何解决?

或者只是如何在 JSON.parse() 之前进行转换:

'[{a: 10, b: 20}]' -> '[{"a": 10, "b": 20}]'

I'm using yargs package to get the arguments.

最佳答案

这似乎是 Windows 和 NPM 以及最终 Node 如何处理引号的问题。

"dev": "node index.js --json-items=\"[{\\\"a\\\": 10, \\\"b\\\": 20}]\""

首先json需要转义一次,windows/node需要再转义一次。另外 ' 似乎也不太好用,所以我推荐 \"

关于javascript - NodeJS - 在 Windows 上解析另一个 JSON 中的 JSON 字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59580668/

相关文章:

javascript - bootstrap popover不显示隐藏的内容包装器

javascript - 文本类型输入域中的上标

javascript - 在 Angular.JS 中查看字段名称和值的更好方法

javascript - Node js + jade 打印在 jade 文件中传递变量

node.js - Faster MediaStream ImageCapture(将媒体流读取为nodejs中的缓冲区)

node.js - 为什么我会在 Node v5.7.0 上收到 "Promise is not defined."错误

javascript - 使用 javascript 或 Lodash 将数组值添加到一个 json 对象中

javascript - 未捕获的类型错误 : undefined is not a promise

javascript - 带有参数的函数值的 JSON

javascript - 如何使用 AngularJS foreach 使用 json 中的键获取特定值