繁体   English   中英

如何从 JSON 获取属性值并使用 node.js 以特定格式将其写入文件

[英]How to get attribute value from JSON and write it in file in specific format using node.js

我有一个 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'
       ]
    }

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

您还没有分享您是如何获取这些数据的,但是由于您为 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);
   }
}

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

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

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 脚本中生成/执行命令行程序。 有关如何使用fs.writeFile或使用child_process例如,请参阅https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

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) ] );

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

此代码有一点风险,但它适用于您的情况

 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM