0

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);
});
2
  • 1
    What exactly is fileName.push(title) supposed to achieve? Commented Jun 5, 2020 at 11:42
  • You've updated your question to what??? It's the exact same question, with put instead of push. What does "to be updating the title" mean? What title??? Commented Jun 5, 2020 at 11:50

3 Answers 3

1
/*
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

Sign up to request clarification or add additional context in comments.

1 Comment

Can you please help me with the following question ! stackoverflow.com/questions/62209482/…
0

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);
})

Comments

0
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))

1 Comment

While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.