Access JSON file data using JavaScript
I have 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 the name and family, which are stored in a JSON file that is loaded using my HTML input.
Is there a way to use an HTML5 file reader or something else?
I do not use server-side programming, they are all client-side.
You will need an HTML5 browser, but it 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>Sam Greenhalghs , .
$(document).on('change', '.file-upload-button', function(event) {
var reader = new FileReader();
reader.onload = function(event) {
var jsonObj = JSON.parse(event.target.result);
alert(jsonObj.name);
}
reader.readAsText(event.target.files[0]);
});<input class='file-upload-button' type="file" />Oops! This can be done using HTML5 FileReader. And it is actually quite simple.
Save json as a .js file and upload it in my example
{
"name": "John",
"family": "Smith"
}
Here the magic happens:
$("#up").change(function(event){
var uploadedFile = event.target.files[0];
if(uploadedFile.type !== "text/javascript" && uploadedFile.type !== "application/x-javascript") {
alert("Wrong file type == " + uploadedFile.type);
return false;
}
if (uploadedFile) {
var readFile = new FileReader();
readFile.onload = function(e) {
var contents = e.target.result;
var json = JSON.parse(contents);
alert_data(json);
};
readFile.readAsText(uploadedFile);
} else {
console.log("Failed to load file");
}
});
function alert_data(json)
{
alert('Name : ' + json.name + ', Family : '+ json.family)
}
Link to this code: http://jsfiddle.net/thomas_kingo/dfej7p3r/3/
(Checking uploadedFile.type is checked only in Chrome and firefox)