Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access data of uploaded JSON file?

I have a html code like this:

<input type="file" id="up" /> <input type="submit" id="btn" /> 

And I have a JSON file like this:

{  "name": "John",  "family": "Smith" } 

And a simple JavaScript function:

alert_data(name, family) {      alert('Name : ' + name + ', Family : '+ family) } 

Now I want to call alert_data() with name and family that stored in JSON file which uploaded using my HTML input.

Is there any way to use an HTML5 file reader or something else?
I'm not using server-side programming, all of them are client-side.

like image 556
Masoud Aghaei Avatar asked Apr 28 '14 15:04

Masoud Aghaei


People also ask

How do I read an uploaded JSON file?

Uploading and processing the JSON file with JavaScript # To actually read the file, we can use the FileReader. readAsText() method. We call it on our reader , and pass in the file to read as an argument. We can access the file using the files property on our file field.

How do I access a JSON file?

JSON files are human-readable means the user can read them easily. These files can be opened in any simple text editor like Notepad, which is easy to use. Almost every programming language supports JSON format because they have libraries and functions to read/write JSON structures.

How do I access parsed JSON data?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.


1 Answers

You will need an HTML5 browser, but this is possible.

(function(){            function onChange(event) {          var reader = new FileReader();          reader.onload = onReaderLoad;          reader.readAsText(event.target.files[0]);      }        function onReaderLoad(event){          console.log(event.target.result);          var obj = JSON.parse(event.target.result);          alert_data(obj.name, obj.family);      }            function alert_data(name, family){          alert('Name : ' + name + ', Family : ' + family);      }         document.getElementById('file').addEventListener('change', onChange);    }());
<input id="file" type="file" />    <p>Select a file with the following format.</p>  <pre>  {    "name": "testName",    "family": "testFamily"  }      </pre>
like image 175
Sam Greenhalgh Avatar answered Oct 09 '22 02:10

Sam Greenhalgh