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

93 Views Asked by At

I want this format

 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

But I get this format after I write the file.

{"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>

Can someone tell me how I can achieve that?

This is my code :

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 = '[email protected]';
        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();

  });

}
1

There are 1 best solutions below

7
On BEST ANSWER

If I've understood correctly the problems start here:

"tags": ${SCHEMA.tags}

You aren't passing that value through JSON.stringify the way you did with earlier values so it's just getting included unencoded, including all the newline characters within it.

There are then several other similarly unencoded values on that line.

Compare how you output categories:

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

"categories": ${categories}

to how you output tags:

"tags": ${SCHEMA.tags}

All that said, it would be easier to avoid building the JSON in such a piecemeal fashion and just use:

logger.write(JSON.stringify(SCHEMA));

If you only want to output certain properties you can use:

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