如何在JavaScript中编辑外部JSON文件? [英] How to edit an external JSON-file in JavaScript?

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

问题描述

我在 Esther Crawford的教程之后创建了一个聊天机器人. 该机器人检查输入用户的字符串并以我的json回答之一进行响应.

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.

例如,如果我说"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."
}

我的问题是:如何在JavaScript中编辑 script.json ?

My question is: How to edit my script.json in JavaScript?

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

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

script.js

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

如何通过在JavaScript中编辑JSON文件来获取用户的未知字符串并将其添加到 script.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 should automatically add the question of the user to the script.json file, ask the user for an answer and then add this answer in the script.json file too.

非常感谢您的帮助!您将在git上找到该项目,其完整代码为此处.

Many thanks for your help! You'll find this project on git with the full code here.

推荐答案

您不能使用客户端脚本将其保存在文件中,而必须使用某些服务器端脚本(例如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 name = 'fileName.json';
var m = JSON.parse(fs.readFileSync(name).toString());
m.forEach(function(p){
    p.name= m.name;
});
fs.writeFileSync(name, JSON.stringify(m));

希望有帮助

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

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