如何使用 node.js 将此 json 格式写入 txt 文件

How to write this json like format on a txt file using the node.js

我想要这种格式

 1   {"index": {"_id": 0}}
 2   { "age_groups" : ["-KmQN3SH7_ ........100000 words in sinle line
 3   {"index": {"_id": 1}}
 4   { "age_groups" : ["-KmQN3SH7_ ........100000 words in sinle line
 5   {"index": {"_id": 2}}
 6   { "age_groups" : ["-KmQN3SH7_ ........100000 words in sinle line
 7   {"index": {"_id": 3}}
 8   { "age_groups" : ["-KmQN3SH7_ ........100000 words in sinle line

但是我写文件后得到这个格式。

{"index": {"_id": 0}}
{ "age_groups" : ["-KmQN3SH7_P73cwZrSmD","-KmQN6Aze7LROyH_cCpP","-"-KmQNKlhHrO0AnnAGybq"],  "needs": ["-Km5n7VJ_X5j2Yj9aG6c","-Km5ncKlPDe8C4nFq6kG"], "categories": ["-KmCtR9mDf_CvwtS3B74","-KmCter6Woj-xM1jPNs4"], "tags": , "title": "Bepanthol - Intensive Κρέμα Προσώπου & Ματιών - 50ml", "code": "113829", "brand": "Bepanthol", "price_bought": "0", "price_sell": "16.05", "weight": "50ml", "description": "<h3><span style="font-size:12px"><strong>Bepanthol</strong></span></h3>

有人可以告诉我如何实现吗?

这是我的代码:

const fs = require('fs');
const jsonfile = require('jsonfile');

var logger = fs.createWriteStream('./Exports/log1.txt', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

function convertProducts_fs() {



  const selectedFile = document.getElementById('inp_products_fs').files[0];
  const filePath = selectedFile.path;
  const fileToRead = filePath;

  jsonfile.readFile(fileToRead, function(err, data) {

    let counter = 0;
    for (let key in data) {

      if (data.hasOwnProperty(key)) {

        let element = data[key];
        let SCHEMA = {};

        SCHEMA.age_groups = [];
        SCHEMA.needs = [];
        SCHEMA.categories = [];
        SCHEMA.tags = [];

        SCHEMA.title = element.title;
        SCHEMA.code = element.custom_id;
        SCHEMA.brand = element.brand;
        SCHEMA.price_bought = element.bought_price;
        SCHEMA.price_sell = element.sell_price;
        SCHEMA.weight = element.weight;
        SCHEMA.description = element.description;
        SCHEMA.uses = element.uses;

        SCHEMA.created = element.timestamp;
        SCHEMA.updated = element.timestamp;
        SCHEMA.image_url = '';
        SCHEMA.added_by = 'admin@gmail.com';
        SCHEMA.status = 'inactive';


        for (let _key1 in element.age_groups) {
          SCHEMA.age_groups.push(_key1);
        }

        for (let _key2 in element.needs) {
          SCHEMA.needs.push(_key2);
        }

        for (let _key3 in element.final_category) {
          SCHEMA.categories.push(_key3);
        }


        SCHEMA.created = element.timestamp;
        SCHEMA.updated = element.timestamp;


        let age_groups = JSON.stringify(SCHEMA.age_groups);
        let needs = JSON.stringify(SCHEMA.needs);
        let categories = JSON.stringify(SCHEMA.categories);

        logger.write(`{"index": {"_id": ${counter}}}`) // append string to your file
        logger.write('\r\n')
        logger.write(`{ "age_groups" : ${age_groups},  "needs": ${needs}, "categories": ${categories}, "tags": ${SCHEMA.tags}, "title": "${SCHEMA.title}", "code": "${SCHEMA.code}", "brand": "${SCHEMA.brand}", "price_bought": "${SCHEMA.price_bought}", "price_sell": "${SCHEMA.price_sell}", "weight": "${SCHEMA.weight}", "description": "${SCHEMA.description}", "uses": "${SCHEMA.uses}" }`) // append string to your file
        logger.write('\r\n')
      }

      counter++;


    }

    logger.end();

  });

}

如果我理解正确,问题就从这里开始:

"tags": ${SCHEMA.tags}

您没有像处理早期值那样通过 JSON.stringify 传递该值,因此它只是以未编码的方式包含在内,包括其中的所有换行符。

该行还有其他几个类似的未编码值。

比较你的输出方式 categories:

let categories = JSON.stringify(SCHEMA.categories);

"categories": ${categories}

你如何输出tags:

"tags": ${SCHEMA.tags}

综上所述,避免以这种零碎的方式构建 JSON 并只使用:

会更容易
logger.write(JSON.stringify(SCHEMA));

如果您只想输出某些属性,您可以使用:

logger.write(JSON.stringify(SCHEMA, ['age_groups', 'needs', /* etc. */]));