I'm a beginner at coding and I'm trying to make a code to compare two uploaded .JSON files but I'm stuck as to how to get the value of the .JSON file.
If i use file1.value => its just showing the path of the file like C://fakepath//
I want to get the content of the files
Here is my code at the moment
<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);
CodePudding user response:
Once the user has set the input, you can dig into the file input to get the file contents like this:
const f = document.querySelector("#file1")
f.files[0].text().then((data) => {
console.log(data)
})
f.files
might contain more than 1 item if you set the multiple
attribute on the input. In your case, you just want the first item.
You might also like to look into the File API
Edit
Wrap your click handler into an async function:
// 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)
}
Here is a codesandbox of what it should look like in the end. https://codesandbox.io/s/comparing-two-uploaded-json-files-39xmp
CodePudding user response:
Here I've two JSON data files and both contain the same following values.
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"
}
]
First I loaded two files. Then read the data in a different textarea (read-only mode). Then compare if both files are matched or not. You can also check it LIVE from here.
<!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>
Note: If also need to compare data also let me know.