1

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

如果我使用 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); 

4

2 回答 2

2

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

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

f.files[0].text().then((data) => {
    console.log(data)
})

f.filesmultiple如果您在输入上设置属性,则可能包含超过 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

于 2021-11-11T04:36:13.273 回答
0

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

第一文件.json

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

第二文件.json

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

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

<!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>

注意:如果还需要比较数据也请告诉我。

于 2021-11-11T05:08:49.750 回答