I have created a little chat bot following the tutorial of Esther Crawford. This bot check the string that enter the user and respond with one of my json answer.
For e
You can't save in a file using client-side script, you have to use some server-side scripting like PHP, NodeJS etc. to save something in a file.
For example in NodeJS you can use the fs library:
fs = require('fs');
var m = JSON.parse(fs.readFileSync('fileName.json').toString());
m.forEach(function(p){
p.name= m.name;
});
fs.writeFile('fileName.json', JSON.stringify(m));
Hope it helps
Unfortunately, without having server-side code - that would take a request & store the file on the server - it is not posible to save files.
However you could use localStorage.
For example:
//If statement to check if localStorage already stored.
if (!localStorage.script) {
localStorage.script = JSON.stringify({
"HELLO": "Hey, I'm so glad you set EstherBot up!",
"I LOVE YOU": "Awh, shucks! I love you too!",
"CONNECT ME": "",
"DISCONNECT": "Roger that, EstherBot is back."
}) ;
}
//This will load the localStorage data into an object in the varaible called botScript
var botScript = JSON.parse(localStorage.script) ;
function saveScript() {
//This will save the current object to the localStorage.
localStorage.script = JSON.stringify(botScript) ;
}
You can read more at http://www.w3schools.com/html/html5_webstorage.asp.
You could also use session storage if you want it to be temporary.
Assuming you got your json already loaded:
var json = '{"hola":"ciao"}';
//Parse the JSON: convert it into an object
var parsedJson =JSON.parse(json);
//add whatever you want
parsedJson.hi = 'bye';
Your json var will look like:
Object {hola: "ciao", hi: "bye"}
Then you can convert the object to string doing JSON.stringify(parsedJson)
and write back to disk/DB if you're manipulating it in your backend (ie.: NodeJs).