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);
Once the user has set the input, you can dig into the file input to get the file contents like this:
f.filesmight contain more than 1 item if you set themultipleattribute 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:
Here is a codesandbox of what it should look like in the end. https://codesandbox.io/s/comparing-two-uploaded-json-files-39xmp