【问题标题】:In Javascript, how to append string values to a JSON object, store it to a file, and retrieve/manipulate it later?在 Javascript 中,如何将字符串值附加到 JSON 对象,将其存储到文件中,并在以后检索/操作它?
【发布时间】:2020-05-16 20:16:25
【问题描述】:

我希望做以下事情;

  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>

【问题讨论】:

  • 你不能用纯 JavaScript 做到这一点。如果你想操作文件,你必须使用 Node
  • 如果无法写入文件,我还是想看看问题问的如何从字符串创建 JSON 对象的逻辑。
  • @Zac 查看JSON.parse()JSON.stringify(),它们将JSON 字符串转换为对象,反之亦然。您可以使用localStoragesessionStorage,但您无法访问浏览器中的实际文件系统。想想如果任何网站的 JS 代码可以读取您计算机上的任何文件,将会有什么样的安全风险。
  • 我希望此代码用于 Cordova 移动应用程序(因此写入/读取文件不是问题),但如果作为 Cordova 代码发布,则没有人回答问题,因此我将其发布为这样。)跨度>

标签: javascript html json file parsing


【解决方案1】:

这是一种创建 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>

【讨论】:

  • 这似乎对我不起作用。我认为输入的值必须推送到 obj 对象。但是,在查看其内容时,Chrome 控制台仅显示“abc {userInput: Array(1)}” {userInput: Array(1)} - 如您所见,Array(1)} 未显示弹出的值进入obj。如何解决这个问题?
猜你喜欢
  • 1970-01-01
  • 2022-01-04
  • 2018-03-12
  • 2019-01-31
  • 2012-01-19
  • 2017-02-23
  • 2020-08-08
  • 2014-04-23
  • 1970-01-01
相关资源
最近更新 更多