如何:在javascript中编辑外部json文件 [英] How to : edit an external json file in javascript

查看:105
本文介绍了如何:在javascript中编辑外部json文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Esther Crawford tuto 之后创建了一个小聊天机器人>。
这个机器人检查输入用户的字符串并用我的一个json答案回复。

I'have created a little chat bot following the tuto of Esther Crawford. This bot check the string that enter the user and respond with one of my json answer.

例如,如果我说hello,机器人会回复嘿,我很高兴你设置了EstherBot !

For example if I say "hello" the bot 'll respond "Hey, I'm so glad you set EstherBot up!"

script.json

{
    "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."
}

我的问题是,如何编辑 script.json javascript中的文件?

My question is , how to edit my script.json file in javascript ?

当用户输入未知字符串时,机器人会回答它不理解的情况。

For the moment when the user enter an unknown string, the bot 'll answer that it doesn't understand .

script.js

if (!_.has(scriptRules, upperText)) {
    return bot.say('Sorry I dont understand').then(() => 'speak');
}

我怎么能得到用户的这个未知字符串并将其添加到我的 script.json 通过在javascript我的json文件中编辑文件?

How could I get this unknown string of the user and add it in my script.json file by editing in javascript my json file ?

我希望我的机器人自己学习,如果他不知道答案,它会自动在 script.json中添加用户的问题文件并询问用户的答案。然后在 script.json 文件中添加此答案。

I want that my bot learn by itself , if he doesn't know the answer it 'll automatically add the question of the user in the script.json file and asked for an answer to the user. And then add this answer in the script.json file too.

要恢复:如何在javascript中编辑json文件?

To resume : How to edit a json file in javascript ?

非常感谢您的帮助!
这里你会在git上找到这个项目的完整代码

Many Thank's for your help ! Here you 'll find this project on git with the full code

ps:我的应用程序是 heroku 的主机。

ps: My app is host on heroku.

推荐答案

你不能使用客户端脚本保存在文件中,你必须使用PHP之类的服务器端脚本,NodeJS等将文件保存在文件中。

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.

例如在NodeJS中你可以使用fs库:

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

希望有所帮助

这篇关于如何:在javascript中编辑外部json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆