比较两个上传的 json 个文件

Comparing two uploaded json files

我是编码初学者,我正在尝试编写代码来比较两个上传的 .JSON 文件,但我不知道如何获取 .[=22 的值=] 文件.

如果我使用 file1.value => 它只是显示文件的路径,如 C://fakepath//

我要获取文件内容

这是我目前的代码

    <input type="file" id="file1" name="file1">
      <input type="file" id="file2" name="file2">
      <button class="check">check</button>

      <div class="output-container">
        <pre id="output1"></pre>
        <pre id="output2"></pre>
      </div>

   
const file1 = document.querySelector("#file1");
const file2 = document.querySelector("#file2");
const check = document.querySelector('.check');

check.addEventListener('click', compare);

// let json1, json2 = false;

file1.addEventListener("change", function () {
  let fr = new FileReader();
  const output1 = document.getElementById("output1");

  fr.onload = function () {
    output1.textContent = fr.result;
  };

  fr.readAsText(this.files[0]);
});

file2.addEventListener("change", function () {
  let fr = new FileReader();
  const output2 = document.getElementById("output2");

  fr.onload = function () {
    output2.textContent = fr.result;
  };

  fr.readAsText(this.files[0]);
});


function getDifference(o1, o2) {
  var diff = {};
  var tmp = null;
  if (JSON.stringify(o1) === JSON.stringify(o2)) return true;

  for (var k in o1) {
    if (Array.isArray(o1[k]) && Array.isArray(o2[k])) {
      tmp = o1[k].reduce(function(p, c, i) {
        var _t = getDifference(c, o2[k][i]);
        if (_t)
          p.push(_t);
        return p;
      }, []);
      if (Object.keys(tmp).length > 0)
        diff[k] = tmp;
    } else if (typeof(o1[k]) === "object" && typeof(o2[k]) === "object") {
      tmp = getDifference(o1[k], o2[k]);
      if (tmp && Object.keys(tmp) > 0)
        diff[k] = tmp;
    } else if (o1[k] !== o2[k]) {
      diff[k] = o2[k]
    }
  }
  return diff;
}

// var d = getDifference(output1.textContent, output2.textContent);
// console.log(d);

// console.log(output1);
// console.log(output2.textContent); 

一旦用户设置了输入,您就可以深入文件输入以获取文件内容,如下所示:

const f = document.querySelector("#file1")

f.files[0].text().then((data) => {
    console.log(data)
})
如果您在输入上设置 multiple 属性,

f.files 可能包含超过 1 个项目。在您的情况下,您只需要第一项。

您可能还想查看 File API


编辑

将您的点击处理程序包装到异步函数中:

// Assign compare function to event listener
const check = document.querySelector(".check");
check.addEventListener('click', compare);

const compare = async () => {

    // Get file inputs
    const file1 = document.querySelector("#file1");
    const file2 = document.querySelector("#file2");

    // Get the file contents by awaiting the promise to resolve
    const contents1 = await file1.files[0].text()
    const contents2 = await file2.files[0].text()

    const difference = getDifference(o1, o2)

}    

这是一个最终应该是什么样子的代码框。 https://codesandbox.io/s/comparing-two-uploaded-json-files-39xmp

这里我有两个 JSON 数据文件,它们都包含相同的以下值。

FirstFile.json

[
  {
    "name": "Raju Ahmed",
    "age": 32,
    "country": "Bangladesh"
  }
]

SecondFile.json

[
  {
    "name": "Raju Ahmed 2",
    "age": 32,
    "country": "Bangladesh"
  },
  {
    "name": "Raju Ahmed 2",
    "age": 32,
    "country2": "Bangladesh"
  }
]

首先我加载了两个文件。然后读取不同文本区域中的数据(只读模式)。然后比较两个文件是否匹配。您也可以从这里查看 LIVE

<!DOCTYPE html>
<html>
<head>
  <style>
     table, td, th {
     border: 1px solid black;
     }
     table {
     width: 100%;
     border-collapse: collapse;
     }
  </style>
</head>
<body>
<form id="jsonFile" name="jsonFile" enctype="multipart/form-data" method="post">
 <fieldset>
    <h2>Json File</h2>
    <table >
       <thead>
          <tr>
             <th>Select First File</th>
             <th>First File Value</th>
             <th>Select Second File</th>
             <th>Second File Value</th>
             <th>Load File</th>
             <th>Compare</th>
          </tr>
       </thead>
       <tr>
          <td><input type='file' id='fileinput'></td>
          <td><textarea readonly disabled id="fileOneData" name="fileOneData" placeholder="First File Data"></textarea></td>
          <td><input type='file' id='fileinput2'>    </td>
          <td><textarea readonly disabled id="fileTwoData" name="fileTwoData" placeholder="Second File Data"></textarea></td>
          <td><input type='button' id='btnLoad' value='Load' onclick='loadFile()'></td>
          <td><input type='button' id='btnCompare' value='Compare' onclick='Compare()'></td>
       </tr>
    </table>
 </fieldset>
</form>
<script type="text/javascript">
 function Compare(){
  var fileOneData = document.getElementById("fileOneData").value;
  var fileTwoData = document.getElementById("fileTwoData").value;
  
  var compareResult= JSON.stringify(fileOneData)===JSON.stringify(fileTwoData);
  if(compareResult){
    alert("Both file matched");
  }
  else{
    alert("Both file not matched");
  }
 }
 
  function loadFile() {
    var input, file, fr;
    if (typeof window.FileReader !== 'function') {
      alert("The file API isn't supported on this browser yet.");
      return;
    }
 
    input = document.getElementById('fileinput');
    input2 = document.getElementById('fileinput2');
    if (!input) {
      alert("Um, couldn't find the fileinput element.");
    }
 else if(!input2){
    alert("Um, couldn't find the fileinput 2 element.");
 }
    else if (!input.files) {
      alert("This browser doesn't seem to support the `files` property of file inputs.");
    }
 else if (!input2.files) {
      alert("This browser doesn't seem to support the `files` property of file inputs 2.");
    }
    else if (!input.files[0]) {
      alert("Please select a file before clicking 'Load'");
    }
 else if (!input2.files[0]) {
      alert("Please select a file 2 before clicking 'Load'");
    }
    else {
      file = input.files[0];
      fr = new FileReader();
      fr.onload = receivedText;
      fr.readAsText(file);
   
   file2 = input2.files[0];
      fr2 = new FileReader();
      fr2.onload = receivedText2;
      fr2.readAsText(file2);
    }
 
    function receivedText(e) {
      let lines = e.target.result;
      var newArrOne = JSON.parse(lines);
      document.getElementById('fileOneData').value=lines;     
   
    }
 
  function receivedText2(e) {
      let lines = e.target.result;    
      var newArrTwo = JSON.parse(lines); 
   document.getElementById('fileTwoData').value=lines
    }
  }
</script>
</body>
</html>

注:如果还需要对比数据也告诉我。