使用Node.js将嵌套的json数组解析为单独的json对象

时间:2017-10-05 02:05:46

标签: javascript json node.js

需要帮助使用Node.js将嵌套数组解析为单独的对象。非常感谢您的帮助。

我需要在最终输出中没有这些 -

"Status": "0",
"Message": "OK",
"Count": "3724",

我需要将以下内容作为单独的json对象 -

  • InvoiceRecords(在json中出现一次)
  • InvoiceRecordHeaderDetails(在json中多次出现)
  • InvoiceRecordSplitDetails(在json中多次出现)
  • InvoiceRecordLineItemDetails(在json中多次出现)
  • InvoiceTaxCodeDetails(在json中多次出现)

拥有以下json数据样本(截断):

{
"Status": "0",
"Message": "OK",
"Count": "3724",
"InvoiceRecords": [
    {
        "InvoiceDate": "8/9/2017 12:00:00 AM",
        "InvoiceLocation": "002",
        "InvoiceNumber": "2004085",
        "InvoiceRecordHeaderDetails": [
            {
                "InvNum": "2004085",
                "Location": "002",
                "InvDate": "8/9/2017 12:00:00 AM"
            }
        ],
        "InvoiceRecordSplitDetails": [
            {
                "UniqueID": "1757391",
                "InvNum": "2004085",
                "Location": "002",
                "InvoiceDate": "8/9/2017 12:00:00 AM"
            }
        ],
        "InvoiceRecordLineItemDetails": [
            {
                "UniqueID": "3939934",
                "InvNum": "2004085",
                "Location": "002",
                "InvoiceDate": "8/9/2017 12:00:00 AM"
            }
        ],
        "InvoiceTaxCodeDetails": [
            {
                "InvoiceDate": "8/9/2017 12:00:00 AM",
                "Location": "002",
                "InvNum": "2004085",
            }
        ]
    }
]

}

更新2

@克里斯-adorna

按照你的指示(我认为),但遇到了障碍(帮助?)

// Parse input file data as json
var jsonContent = JSON.parse(fs.readFileSync(inputFile, 'utf8'));

//1. Create 4 empty arrays, one each for record header, splits, line items and tax code details
var recordHeader;
var splits;
var lineItems;
var taxCodes;

//2. Use a forEach function to iterate through InvoiceRecords

var i;
for (i = 0; i < jsonContent.length; i++) {
    var record = jsonContent[i].InvoiceRecords;
};
console.log(record);

第2步没有得到任何东西,但未定义&#39;在控制台中。

1 个答案:

答案 0 :(得分:0)

从字面上理解你的问题,尤其是这一部分:“将每个数组输出到单独的json文件”,尝试以下方面:

  1. 创建4个空数组,每个数组用于记录标题,拆分,行 项目和税码详细信息
  2. 使用forEach function来迭代InvoiceRecords
  3. 对于每个iteratee对象,使用for...of statement进行迭代 通过Object.entries
  4. 使用条件表达式,如果键===你的目标(即 'InvoiceTaxCodeDetails'),push将值放入适当的值 阵列
  5. forEach功能完成后,then使用原生fs 模块将每个数组的内容写入JSON文件