javascript - Nodejs && JSON : select value by key

标签 javascript node.js bash shell

我有这个简单的 JSON:

{
    "list": [
        {"name": "item-1", "url": "http://item-1.com"},
        {"name": "item-2", "url": "http://item-2.com"},
        {"name": "item-3", "url": "http://item-3.com"}
    ]
}

我无法获取任何指定名称的网址。
例如,如果nodejs程序名为jsonpareser.js:

node jsonpareser.js "item-1"

我想打印网址“http://item-1.com”。

jsonparser.js 中的脚本是:

/* Get the parameter I want to search */
var item=process.argv.slice(2);

/* Specify JSON file path*/    
var file = './file.json';
/* Load file */
var items = require(file);

/* Iterate on elements */
for ( var i = 0; i < items.length; i++ ) {
    if ( typeof items[i] == item ) {
        console.log(items[i]);
    }
}

最佳答案

编辑:

您添加了新代码;我也修复了你的“jsonparser.js”:

/* Get the parameter I want to search */
var item=process.argv.slice(2);

/* Specify JSON file path*/    
var file = './file.json';

/* Load file */
var items = require(file).list;

/* Iterate on elements */
for (var i in items)
{
    if (items[i].name==item)
    {
        console.log(items[i].url);
        break;
    }
}
<小时/>

使用process.argv:

  • arg 0:包含第一个参数,用于运行代码,即“node”
  • arg 1:包含第二个参数,运行代码的路径,即[script-name]
  • arg 2:必须存在,将是您的参数,“item-2”或未定义。

希望这有帮助!

var list    =   
[
    {"name": "item-1", "url": "http://item-1.com"},
    {"name": "item-2", "url": "http://item-2.com"},
    {"name": "item-3", "url": "http://item-3.com"}
];

//  ensure at least TWO arguments are given
//  first argument is node=[script path]
if (process.argv.length>2)
{
    //  assume second argv contains your name.
    var name    =   process.argv[2];

    //  iterate list.
    for (var i in list)
    {
        //  check for a match.
        if (list[i].name==name)
        {
            //  print data to console.
            console.log(list[i].url);

            //  print with success.
            process.exit(0);
        }
    }

    //  end of search, no items found, end with exit code.
    console.log("No items found.");
    process.exit(1);
}

//  no argument given, error and exit.
console.log("No arguments given, please give an argument!");
process.exit(1);

关于javascript - Nodejs && JSON : select value by key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23221792/

相关文章:

javascript - 是否可以在 angular-localForage 中创建多个数据存储?

javascript - 如何从异步调用返回响应?

node.js - 使用 v8 分析 nodejs

javascript - 处理Node js中的多个错误

linux - 如何使用 Sed 搜索将整个单词替换为文件中的字符串匹配项

javascript - 进入网站时滚动到 div

javascript - AngularJS:为什么我的 $interval 不停止?

node.js - 如何获取向 Heroku 上运行的 Node 服务器发送 GET 的服务器的 IP?

java - 是否可以仅使用纯 Java 编写类似于 bash 的 shell?

linux - shell 脚本内部的时间控制