2

Hello every expert and student like me. If I want to upload a local JSON file to the HTML and print it out, is there any way to do it?

The following is what is in the JSON file

{
"Result" : [
     {"title":"JSON", "url":"http://json.org",
"description":"the home page for JavaScript Object
Notation"},

{"title":"XML", "url":"http://xml.org", 
"description":"the home page for Extensible Markup Language"}
]
}

And these lines are my code for uploading a file.

<form action="/action_page.php">
Upload a file:
<input type="file" id="uploadedFile" name="uploadedFile[]" />

These lines of code give me a button to upload a file, and I want to print the element out like the following.

Output

I want to print the JSON file out, and by doing that I tried to use for loop, but I don't know which part of the code is referencing the uploaded file so I can start writing my for loop? (Or maybe it is not even existed in my written code.) Can I do this?

var myJSON_object = input;

to use myJSON_object as the reference to the input JSON file? Also, a great appreciation for a better way of printing the JSON file out.

xxColderxx
  • 53
  • 6
  • The below link will helps you get the content of json file https://stackoverflow.com/questions/23344776/access-data-of-uploaded-json-file-using-javascript after getting that you can do your business logic – saravana Nov 02 '19 at 17:12
  • It is pretty helpful, thank you. – xxColderxx Nov 02 '19 at 18:27

1 Answers1

1

<html>
<style>
#out pre{
    background-color: #bdc3c3;
border:1px solid #fff;
border-radius:5px;
padding:10px;
}
</style>
<head>
<input id="file" type="file" />
<div id="out"></div>
<script>
const out = document.getElementById('out');
(function(){
    
    function onChange(event) {
        var reader = new FileReader();
        reader.onload = onReaderLoad;
        reader.readAsText(event.target.files[0]);
    }

    function onReaderLoad(event){

        var obj = JSON.parse(event.target.result);
        for(let x in obj.Result){
       createElement(obj.Result[x]);
      
}
}

function createElement(obj){
 let h1= document.createElement('h1');
 h1.innerText = obj.title
 let anchor = document.createElement('a');
 anchor.href = obj.url;
  
anchor.innerText=obj.url.replace('http://','');
 let p = document.createElement('p');
 p.innerText = obj.description;
 let pre= document.createElement('pre');

pre.appendChild(h1);pre.appendChild(anchor);pre.appendChild(p);
out.appendChild(pre);
}
  
    
   
    document.getElementById('file').addEventListener('change', onChange);

}());
</script>
</head>
saravana
  • 331
  • 1
  • 5