【发布时间】:2020-05-16 20:16:25
【问题描述】:
我希望做以下事情;
- 将 CSV 文件加载到程序内存中的数组中(abc、def、ghi 等)
- 用户输入文本并单击添加(例如,先定义,然后是 ghi)
- 如果找到匹配项,我们将创建一个新的 JSON 数组(“def”:true、“ghi”:true 等)
这是我的代码:
csv = "abc,def,ghi,jkl,mno";
function myFunc(e) {
var myArray = csv.split(',');
console.log(myArray[0]);
var input = document.getElementById("userInput").value;
if (myArray.indexOf(input) > -1) {
//In the array - So, we create a new file and add JSON content in it - how? - need to save it in this format - "abc": "true", "def": "true" and so on
alert("The input you entered is valid.");
} else {
//Not in the array
alert("The input you entered is not valid.");
}
}
//How do I read the JSON object from the file later and then parse it back as a JSON object variable?
<form>
<div class="group">
<input type="text" required id="userInput">
<span class="highlight"></span>
<span class="bar"></span>
<label>Enter Input:</label>
</div>
<div class="group">
<input class="button" type="submit" value="Submit" onclick="myFunc(this)">
</div>
</form>
【问题讨论】:
-
你不能用纯 JavaScript 做到这一点。如果你想操作文件,你必须使用 Node
-
如果无法写入文件,我还是想看看问题问的如何从字符串创建 JSON 对象的逻辑。
-
@Zac 查看
JSON.parse()和JSON.stringify(),它们将JSON 字符串转换为对象,反之亦然。您可以使用localStorage或sessionStorage,但您无法访问浏览器中的实际文件系统。想想如果任何网站的 JS 代码可以读取您计算机上的任何文件,将会有什么样的安全风险。 -
我希望此代码用于 Cordova 移动应用程序(因此写入/读取文件不是问题),但如果作为 Cordova 代码发布,则没有人回答问题,因此我将其发布为这样。)跨度>
标签: javascript html json file parsing