1

I have a javascript object like this

    var data = {
    "person": {
        "name": "John Doe",
        "address": "N.Y City",
        "city": "N.Y",
        "country": "USA",
        "phone": "Ph: 12345"
  }

I want to print it like this: Person.Name----Person.Address----Person.Phone in a txt file. Until now I am able to do so with console.log like this

console.log(data['person']['name'] + "----" + data['person']['address'] + "----" + data['person']['phone'])

And the output in console is: "John Doe ---- N.Y City ---- Ph: 12345"

I don't want to print all the values of the json. I want to print some of these and also I want to have this between them "----".

Is it possible to print this in a txt file? I haven't fine anything yet.

marissalianam
  • 75
  • 5
  • 16

1 Answers1

1

In the Node.js context, you can do it this way:

const fs = require('fs');
const yourObject = {
 // ...addProperties here.
}

fs.writeFile("/path/to/save.txt", JSON.stringify(yourObject), 'utf8', function (err) {
    if (err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 

or with async version writeFileSync()

fs.writeFileSync("/path/to/save.txt", JSON.stringify(yourObject), 'utf8')

In the Browser Context You can do this:

// Function to download data to a file
function download(data, filename, type) {
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob) // IE10+
        window.navigator.msSaveOrOpenBlob(file, filename);
    else { // Others
        var a = document.createElement("a"),
                url = URL.createObjectURL(file);
        a.href = url;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        setTimeout(function() {
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);  
        }, 0); 
    }
}

after declaring that function, do this:

download(JSON.stringify(yourObject), 'file', 'txt') // file is filename, and txt is type of file.
Nam G VU
  • 33,193
  • 69
  • 233
  • 372
Daksh M.
  • 4,589
  • 4
  • 30
  • 46
  • 1
    Is there any solution like this in browser context? – marissalianam Dec 22 '17 at 13:50
  • @marissalianam added browser context too – Daksh M. Dec 22 '17 at 13:54
  • Great! Now we drink :D – Daksh M. Dec 22 '17 at 14:08
  • Can I ask you one more thing? I need to write a second line with person data. Is this possible with some change line character or something? For example I need something like this JSON.stringify(data['person']['name']+"----"+data['person']['address'] + ??? + data['person']['phone']) where the phone will be in the next line. Thanksss – marissalianam Dec 22 '17 at 20:24