有什么方法可以在签入Web应用程序上本地更新JSON对象?

时间:2019-03-18 17:19:01

标签: javascript json

我学习了如何从本地JSON文件写入csv对象。但是,我正在设计一个使用javascript的简单签入Web应用程序,并且我想在本地更新json文件。我问SO社区如何在javascript中更新json对象,人们建议使用NodeJS Express框架,这对我来说是全新的和复杂的。我在想如果我可以简单地在本地更新json对象,并想学习此任务的高效javascript解决方案。

基本上,我有本地母亲json文件,将其用作简单的数据库来检查记录,并且我有可以写入为新json对象的源csv文件,因此我的程序想在新json中比较记录母亲json文件中的对象。

这是我尝试过的

在此脚本中,我能够从本地JSON文件在控制台上写入和打印csv对象,并且能够检查手动输入的记录是否在json对象中。

document.getElementById('uinInput').onkeypress = function(e) {
  if (e.keyCode == 13) {
    checkId();
    e.preventDefault();
    return false;
  }
}

function checkId() {
  var typedUIN = document.getElementById('uinInput').value;
  console.log(typedUIN.length);
  if (typedUIN.length == 9) {

    loadDoc(typedUIN);

  }
}

function loadDoc(uinNum) {
  console.log(uinNum);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var json = JSON.parse(this.responseText);
      var jsonString = JSON.stringify(this.responseText, null, 4);
      console.log(json);
      var i;

      /* Searches the JSON file for matching UIN number */
      for (i = 0; i < json.length; i++) {
        /* When match is found, display information about the user associated to the UIN */
        if (json[i].uin == uinNum) {
          json[i].studentInfo["checkin"] = true;
          document.getElementById("userInfo").innerHTML = "<u>User Info: </u>";
          document.getElementById("userInfo").innerHTML += "<br>Name: " + json[i].studentInfo["firstName"] + " " + json[i].studentInfo["middleName"] + " " + json[i].studentInfo["lastName"];
          document.getElementById("userInfo").innerHTML += "<br>UIN: " + json[i].uin;
          document.getElementById("userInfo").innerHTML += "<br>RSVP: " + json[i].studentInfo["rsvpStatus"];
          break; //Match is found, stop search
        } else {
          document.getElementById("userInfo").innerHTML = "<u>User Info: </u>" + "** User Not Found **";
        }
      }
      console.log(json)
    }
  };
  xhttp.open("GET", "https://gist.githubusercontent.com/extempl/40cc998d1624dd0130871a3c5f1d0256/raw/2136b294baff1f7b611523dce91c5e9b8006d7e2/test.json", true); //opens and gets the contents from json file
  xhttp.send();
}
// convert csv2json
function convertToJson(inputCsv) {
  const arrayCsv = inputCsv.split(',').map(s => s.replace(/"/gi, '').trim())
  const outputJson = [];

  for (let i = 6; i < arrayCsv.length; i += 6) {
    const [date, firstName, middleName, lastName, uin, rsvpStatus] =
    arrayCsv.slice(i, i + 6)
    outputJson.push({
      uin,
      studentInfo: {
        firstName,
        middleName,
        lastName,
        rsvpStatus
      }
    });
  }
  return outputJson;
}
/* Input CSV data needs to be written as new json object*/
const csv = `"Timestamp", "Enter First Name:", "Enter Middle Initial", 
    "Enter Last Name:", "Enter UIN:", "Are you attending the event?",
    "2019/02/22 12:41:56 PM CST", "Jonathan", "Samson", "Rowe", "123456789", 
    "No", "2019/02/22 12:44:56 PM CST", "phil", "Aspilla", "beltran", "123456788", 
    "Yes"`
const json = convertToJson(csv);
console.log(json);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<body>
  <p>Manually enter UIN if card swipe not applicable:</p>
  <form id="manualForm">
    UIN:<br>
    <input type="text" id="uinInput" value="" required minLength="9" maxLength="9">
    <br>
    <button id="checkinBtn" type="button" onclick="checkId()">Manual Checkin</button>
  </form>
  <p>Select local CSV File:</p>
  <input id="csv" type="file">
  <output id="out"> input file content</output>
  
  <div id = "userInfo" ><u>User Info: </u></div>
</body>

我是javascript网络开发的新手,我想学习相当简单的解决方案。谁能指出我如何做到这一点?任何想法?谢谢

更新

更新后的新JSON对象可以在最后与母JSON文件集成,因为我创建了模板JSON对象来存储最终写为csv文件的用户数据。

1 个答案:

答案 0 :(得分:2)

代替for

var foundEntry = json.find(function (row) {
  return row.uin == uinNum;
} )

if (foundEntry) {
  foundEntry.studentInfo["checkin"] = true;
} else {
  json.push({
    uin: uinNum.toString(),
    studentInfo: {} //  empty object, you can fill it with data you need
  })
}

console.log(json) // result of the modifying you can use for further CSV generation.

像这样:

document.getElementById('uinInput').onkeypress = function(e) {
  if (e.keyCode == 13) {
    checkId();
    e.preventDefault();
    return false;
  }
}

function checkId() {
  var typedUIN = document.getElementById('uinInput').value;
  console.log(typedUIN.length);
  if (typedUIN.length == 9) {

    loadDoc(typedUIN);

  }
}

function loadDoc(uinNum) {
  console.log(uinNum);
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var json = JSON.parse(this.responseText);
      var jsonString = JSON.stringify(this.responseText, null, 4);
      console.log(json);
      var i;

      /* Searches the JSON file for matching UIN number */
      var foundEntry = json.find(function(row) {
        return row.uin == uinNum;
      })

      if (foundEntry) {
        foundEntry.studentInfo["checkin"] = true;
        document.getElementById("userInfo").innerHTML = "<u>User Info: </u>";
          document.getElementById("userInfo").innerHTML += "<br>Name: " + foundEntry.studentInfo["firstName"] + " " + foundEntry.studentInfo["middleName"] + " " + foundEntry.studentInfo["lastName"];
          document.getElementById("userInfo").innerHTML += "<br>UIN: " + foundEntry.uin;
          document.getElementById("userInfo").innerHTML += "<br>RSVP: " + foundEntry.studentInfo["rsvpStatus"];
      } else {
        json.push({
          uin: uinNum.toString(),
          studentInfo: {} //  empty object, you can fill it with data you need
        });
        document.getElementById("userInfo").innerHTML = "<u>User Info: </u>" + "** User Not Found **";
      }
      
      console.log(json)
    }
  };
  xhttp.open("GET", "https://gist.githubusercontent.com/extempl/40cc998d1624dd0130871a3c5f1d0256/raw/2136b294baff1f7b611523dce91c5e9b8006d7e2/test.json", true); //opens and gets the contents from json file
  xhttp.send();
}
// convert csv2json
function convertToJson(inputCsv) {
  const arrayCsv = inputCsv.split(',').map(s => s.replace(/"/gi, '').trim())
  const outputJson = [];

  for (let i = 6; i < arrayCsv.length; i += 6) {
    const [date, firstName, middleName, lastName, uin, rsvpStatus] =
    arrayCsv.slice(i, i + 6)
    outputJson.push({
      uin,
      studentInfo: {
        firstName,
        middleName,
        lastName,
        rsvpStatus
      }
    });
  }
  return outputJson;
}
/* Input CSV data needs to be written as new json object*/
const csv = `"Timestamp", "Enter First Name:", "Enter Middle Initial", 
    "Enter Last Name:", "Enter UIN:", "Are you attending the event?",
    "2019/02/22 12:41:56 PM CST", "Jonathan", "Samson", "Rowe", "123456789", 
    "No", "2019/02/22 12:44:56 PM CST", "phil", "Aspilla", "beltran", "123456788", 
    "Yes"`
const json = convertToJson(csv);
console.log(json);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<body>
  <p>Manually enter UIN if card swipe not applicable:</p>
  <form id="manualForm">
    UIN:<br>
    <input type="text" id="uinInput" value="" required minLength="9" maxLength="9">
    <br>
    <button id="checkinBtn" type="button" onclick="checkId()">Manual Checkin</button>
  </form>
  <p>Select local CSV File:</p>
  <input id="csv" type="file">
  <output id="out"> input file content</output>

  <div id="userInfo"><u>User Info: </u></div>
</body>