I have a json file that looks something like this. I need to write a JS code that will parse through this file and read specific elements of the file like sensor_state of the first element and write to the specific element like change the sensor_state of "sensor_id": "302CEM/lion/light1" to on. this is what i have tried. I had a few thoughts on how to to go about it. trying to treat it like an array, sensor_state[0] will mean the first group, sensor_state[1] would mean the second one and so on. the other way is to have a name i.e light_1 before each group/object to have code that says sensor_data[light1][sensor_state] = "off" but i am unable to structure the json file to do either. Any suggestions
{
"sensor_data": [
{
"sensor_id": "302CEM/lion/light1",
"sensor_state": "off"
},
{
"sensor_id": "302CEM/lion/light2",
"sensor_state": "off"
}
]
}
const fs =
require('fs');
var data = []
//To Read from the JSON File, dont know if this still needed
fs.readFile('datajson.json', (err,data) => {
if (err) throw err;
var sensor = JSON.parse(data);
var stringy = JSON.stringify(data)
console.log(stringy.sensor_state[0]);
}
)
JSON.parse
instead of working with the string that JSON.stringify
returns.JSON.stringify
. Then call fs.writeFile to actually write the contentYour code will look like this
const fs = require('fs');
const fileName = './data.json';
fs.readFile(fileName, (errRead, content) => {
if (ererrReadr) throw errRead;
let data = JSON.parse(content);
// Change the "sensor_id" of the first item in "sensor_data"
data.sensor_data[0].sensor_id = 'this is a new ID';
// Write back new JSON
fs.writeFile(fileName, JSON.stringify(data), errWrite => {
if (errWrite) throw errWrite;
console.log('New data has been saved');
});
});
I had a few thoughts on how to to go about it. trying to treat it like an array
It is an array, so it only makes sense to treat it like one.