【问题标题】:How to get attribute value from JSON and write it in file in specific format using node.js如何从 JSON 中获取属性值并使用 node.js 以特定格式将其写入文件
【发布时间】:2020-03-19 09:58:04
【问题描述】:

我有一个 test.json 文件,格式如下,我只想从该文件中获取链接值:

从文件系统输入文件:

{
    "5cacd1333105": {
        "type": "CORR-ID",
        "environment": "amazon",
        "tags": [
            {
                "name": "EC-6S0005704A8324S98020",
                "source": "amazonstage2ma_paymentapiplatserv#TOKEN",
                "flags": [
                    "FLAG_DYNAMIC_VALUE",
                    "FLAG_ID_LOOKUP_SUPPORTED"
                ]
            }
        ],
        "callSummary": [
            {
                "colo": "lvs",
                "pool": "slingshotrouter",
                "machine": "stage21007",
                "apiName": "GET",
                "status": "0",
                "duration": 13400.0,
                "calls": null,
                "hints": null,
                "msgTime": 1574314991130,
                "link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
            },
            {
                "colo": "lvs",
                "pool": "slingshot",
                "machine": "stage21029",
                "apiName": "GET",
                "status": "0",
                "duration": 13368.0,
                "calls": null,
                "hints": null,
                "msgTime": 1574314991162,
                "link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
            },


            {
                "colo": "lvs",
                "pool": "msmaster_userbridgedomainserv",
                "machine": "amazon1int-g_userbridgedomainserv_22",
                "apiName": "POST",
                "status": "0",
                "duration": 15.0,
                "calls": null,
                "hints": null,
                "msgTime": 1574315001625,
                "link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
            }

        ],
        "partial": false
    }
}

我想从上面的文件中获取以下详细信息:

    "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
    "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j"
    "https://www.amazon.qa.pilot.com/Tid-02341723424i842424"

我只想按以下格式写入 test.js 文件。

    module.exports = 
    {
       fileNames:[
        'https://www.amazon.qa.pilot.com/Tid-942342192424j2j234',
        'https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j',
        'https://www.amazon.qa.pilot.com/Tid-02341723424i842424'
       ]
    }

我不知道如何获取这些详细信息。有人可以分享我对此的一些意见吗?

【问题讨论】:

标签: javascript node.js json node-modules


【解决方案1】:

这段代码有一点风险,但它在你的情况下可以工作

const data = {
    "5cacd1333105": {
        "type": "CORR-ID",
        "environment": "amazon",
        "tags": [
            {
                "name": "EC-6S0005704A8324S98020",
                "source": "amazonstage2ma_paymentapiplatserv#TOKEN",
                "flags": [
                    "FLAG_DYNAMIC_VALUE",
                    "FLAG_ID_LOOKUP_SUPPORTED"
                ]
            }
        ],
        "callSummary": [
            {
                "colo": "lvs",
                "pool": "slingshotrouter",
                "machine": "stage21007",
                "apiName": "GET",
                "status": "0",
                "duration": 13400.0,
                "calls": null,
                "hints": null,
                "msgTime": 1574314991130,
                "link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
            },
            {
                "colo": "lvs",
                "pool": "slingshot",
                "machine": "stage21029",
                "apiName": "GET",
                "status": "0",
                "duration": 13368.0,
                "calls": null,
                "hints": null,
                "msgTime": 1574314991162,
                "link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
            },


            {
                "colo": "lvs",
                "pool": "msmaster_userbridgedomainserv",
                "machine": "amazon1int-g_userbridgedomainserv_22",
                "apiName": "POST",
                "status": "0",
                "duration": 15.0,
                "calls": null,
                "hints": null,
                "msgTime": 1574315001625,
                "link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
            }

        ],
        "partial": false
    }
};

const jsonDAta = JSON.stringify(data,null,null);

const resArr = (jsonDAta.match(/"link":"[^"]+"/g)||[]).map(el=>JSON.parse(`{${el||''}}`).link)

console.log(resArr);

【讨论】:

  • 我收到错误消息 const resArr = jsonDAta.match(/"link":"[^"]+"/g).map(el=>JSON.parse({${el}}) .link) ^ TypeError: Cannot read property 'map' of null at Module._compile (internal/modules/cjs/loader.js:777:30) at Object.Module._extensions..js (internal/modules/cjs/loader .js:788:10) 在 Module.load (internal/modules/cjs/loader.js:643:32) 在 Function.Module._load (internal/modules/cjs/loader.js:556:12) 在 Function. Module.runMain (internal/modules/cjs/loader.js:840:10) 在 internal/main/run_main_
  • @ArrcanaMohan 我在stringify 中添加了null 参数,也许现在一切正常,我在浏览器控制台和sn-p 中检查了这段代码。一切顺利
【解决方案2】:

看起来5cacd1333105 是一个动态键,所以它可能会改变,并且可能有不止一个这样的随机键,所以你可以使用像这样的for... in 循环来循环每个键(prop)对象:

const d = require('./test.json');

for(let prop in d){
  console.log(d[prop])
}

然后您可以看到唯一相关的属性是 callSummary 数组,因为它包含链接数据。因此,您可以循环数组以提取链接数据。

for(let prop in d){
  const obj = d[prop];
  const links = obj.callSummary.map(({link}) => link);
  console.log(links);
}

上面使用.map回调中的解构从callSummary中的对象中提取链接字符串,返回links中的链接字符串数组。

但是,由于外部for... in循环,我们仍然需要考虑多链接的一般情况。

要将链接组合成一个数组,您可以将循环外的链接声明为一个空数组,然后直接推送到该数组,如下所示:

const links = [];
for(let prop in d){
  const obj = d[prop];
  links.push(obj.callSummary.map(({link}) => link));
}
console.log(links);

最后,您想将该数据写入文件。你可以使用fs 或者你可以从你的node.js 脚本中生成/执行一个命令行程序。请参阅https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback 了解如何使用fs.writeFile 或使用child_process,例如

const d = require('./test.json');
const path = require('path');
const { spawn } = require( 'child_process' );
const links = [];
for(let prop in d){
  const obj = d[prop];
  links.push(obj.callSummary.map(({link}) => link));
}
const filename = `links-${Date.now()}.js`;
console.log(`Outputting links to ${filename}`);
const echo = spawn( 'echo', [ `
module.exports = 
    {
       fileNames:[
           ${JSON.stringify(links, false, 2)}
       ]
    }
`, '>', path.join(process.cwd(), filename) ] );

注意反引号的使用。 (我没有测试最后一点,但它应该可以工作)。

【讨论】:

    【解决方案3】:

    你没有分享你是如何获取这些数据的,但是由于你为 node.js 添加了一个标签,我假设你是在服务器端这样做的。

    在确保收到的数据是 JSON 格式(使用 JSON.parse)并且有效后,要获取您需要的特定字段,您可以执行以下操作:

    let links = [];
    let callSummary = json['5cacd1333105'].callSummary
    for (let index = 0; index < callSummary.length; index++) {
       let call = callSummary[index];
       if (call && call.link) {
          links.push(call.link);
       }
    }
    

    在此之后,您将拥有数组链接中的所有链接,您可以对它们做任何您想做的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多