Rahul
Rahul

Reputation: 759

How to write a string value to json file in Node js?

Am new to Javascript and node.js. Please help me resolving the below issue . I want to update the key 'title' in 'testdata.json' file for the set 'LANG>TEST2>Default' .

testdata.json :

{
    "LANG": {
        "TEST1": {
            "Default": {
                "key1": "value1",
                "key2": "value2"
            },
            "Set1": {
                "key1": "value1",
                "key2": "value2"
            }
        },
        "TEST2": {
            "Default": {
                "key1": "value1",
                "key2": "value2",
                "title": "test-name-05252020-4786",

            }
        },

    }
}

I have the below function but its throwing the error as :

TypeError: fileName.put is not a function


writeToJSON= function(){

    const fs = require('fs');
    const fileName = './testdata';
    let title = "test-name-06052020-1712";

    fileName.put(title);

    fs.writeFile(testdata.json, JSON.stringify(testdata), function writeJSON(err) {
         if (err) return console.log(err);
        console.log(JSON.stringify(testdata));
        console.log('writing to ' + fileName);
});

Upvotes: 0

Views: 147

Answers (3)

Ahmed Magdy
Ahmed Magdy

Reputation: 1226

const fs = require('fs')



let Data = JSON.parse(fs.readFileSync('./testdata.json')) 
Data.LANG.TEST2.Default.title = "test-name-06052020-1712";
fs.writeFileSync('./testdata.json', JSON.stringify(Data))

Upvotes: 0

Paul Zaslavskij
Paul Zaslavskij

Reputation: 654

/*
get readFile and writeFile functions to work with files in filesystem
from 'fs' module. ".promises" - is the way to work with readFile and writeFile
in promise-style, without callback-hell
*/
const {readFile, writeFile} = require('fs').promises
/* first, define path to your file, using template string, where
${__dirname} - is a system variable, that provides your current folder where 
your script is running
*/
const jsonFilePath = `${__dirname}/testdata.json`

/*i have put all the code in async function, it gives me an opportynity
to use 'await' statement inside of it */

async function jsonMagic() {

    //read and parse your json-file from the file-system
    let parsedJSON = JSON.parse(await readFile(jsonFilePath))

    //set the value you need
    parsedJSON.LANG.TEST1.Default.title = "test-name-06052020-1712"

    /*write new file, don't forget to stringify json before you 
    write it on the disk*/

    writeFile(`${__dirname}/newfile.json`, JSON.stringify(parsedJSON, 2, 2)).then(()=>{
        console.log('hey, you did it!')
    })
}

//call your function
jsonMagic()

Also, i tried your json-file and parsing was failed until i removed commas on the last statements, here is valid json:

{
"LANG": {
    "TEST1": {
        "Default": {
            "key1": "value1",
            "key2": "value2"
        },
        "Set1": {
            "key1": "value1",
            "key2": "value2"
        }
    },
    "TEST2": {
        "Default": {
            "key1": "value1",
            "key2": "value2",
            "title": "test-name-05252020-4786"

        }
    }

}

}

tested it in node.js version 12.17.0

Upvotes: 1

Sagar
Sagar

Reputation: 1424

You need to first readJson file and than you can treat data as normal Objects.

let rawData = fs.readFileSync('./testdata.json')
let data = JSON.parse(rawData);
data.LANG.TEST1.Default.title = "test-name-06052020-1712"

fs.writeFile("testdata2.json", JSON.stringify(data), function writeJSON(err) {
    if (err) return console.log(err);
})

Upvotes: 0

Related Questions