简体   繁体   中英

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

I am looking to do the following;

  1. Load a CSV file into program memory into an array (abc, def, ghi etc.)
  2. The user inputs text and clicks Add (say, def first, later ghi)
  3. If a match is found, we create a new JSON array ("def": true, "ghi": true etc.)

Here is my code:

 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>

Here is a way for creating the JSON object

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM