【问题标题】:Node.js eval var json parseNode.js eval var json 解析
【发布时间】:2012-11-12 13:11:34
【问题描述】:

我正在尝试制作一个小型解析器,它接收 json 字符串和获取路径:

var args = process.argv;
var jsonToBeParsed = args[2];
var path = args[3];

var result = JSON.parse(jsonToBeParsed);

console.log(result);
console.log(result.path);

我用

来称呼它
node parser.js '{"asd":"123", "qwe":"312"}' 'asd'

它给了我undefined

我认为它必须通过一些 eval 函数来完成,但我对 node/JS 没有太多经验。 我该如何解决这个问题?我需要从命令行获取结果。

编辑:我期待第二个日志中出现“123”。谢谢@Esailija,这个问题不太清楚......

【问题讨论】:

  • 对我来说很好,当然 json 中没有 path 以便按预期记录 undefined
  • 你读过我的cmets吗?甚至是问题的标题?

标签: json bash node.js


【解决方案1】:

我认为您正在尝试使用动态属性,您不能使用.path,因为它的字面意思是.path 属性。

试试这个:

console.log(result);
console.log(result[path]);

如果是path === "asd",那么它会起作用,静态等效于result["asd"]result.asd

【讨论】:

  • 感谢 Esailija。这里的另一个问题:如果我有像 {"asd":{"qwe":"123", "ert":"465"}} 这样的 Json,我尝试了 result["asd"]["qwe"] 并给了我正确的值“123”。但是还有其他方法可以检索该值吗?(我正在尝试一些类似 result[asd.qwe] 但没有运气的表达式)
  • @Federico result[path1][path2] 如果path1"asd" 并且"path2""qwe"
  • 是的,可以,但是有没有办法以这种方式结果[asd.qwe]?因为我想用 2 个参数、JSON 和完整路径(即“asd.qwe”)调用该应用程序
  • 好吧,您还必须解析点的输入并拆分点上的路径。类似 pathArray = args[3].split('.');然后根据数组的长度等构造查询。
【解决方案2】:

要添加到@Esailija 的答案:

node parser.js '{"path": "123"}' 'asd'

将返回123。点表示法需要属性名称。如果您有动态属性名称,则需要使用方括号表示法。

console.log(result['ads']);
// But what you want is:
console.log(result[path]); // 'path' is a variable with the correct string

【讨论】:

    【解决方案3】:

    我想将 json 解析器嵌入到 git 别名中,以在 bash 中获取 json 节点(使用节点)

    node -e "console.log(JSON.parse(process.argv[1]).foo.bar)" '{"foo":{"bar":"Hello World"}}'

    【讨论】:

    • 也可以用node -p去掉console.log()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-06
    • 1970-01-01
    • 2011-09-23
    • 2015-01-07
    • 2011-05-28
    • 2013-02-15
    • 2020-12-15
    相关资源
    最近更新 更多