簡體   English   中英

在 Javascript 中,如何將字符串值附加到 JSON 對象,將其存儲到文件,並在以后檢索/操作它?

[英]In Javascript, how to append string values to a JSON object, store it to a file, and retrieve/manipulate it later?

我正在尋找執行以下操作;

  1. 將一個 CSV 文件加載到程序存儲器中並放入一個數組(abc、def、ghi 等)
  2. 用戶輸入文本並單擊添加(例如,先定義,然后是 ghi)
  3. 如果找到匹配項,我們會創建一個新的 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>

這是一種創建 JSON 對象的方法

 var obj={'userInput':[]}; function myFunc(e) { obj.userInput.push(document.querySelector('#userInput').value) console.log(obj) }
 <form> <div class="group"> <label>Enter Input:</label> <input type="text" required id="userInput"> <span class="highlight"></span> <span class="bar"></span> </div> <div class="group"> <input class="button" type="button" value="Submit" onclick="myFunc(this)"> </div> </form>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM