reading and writing json file using javascript [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to read and write into file using JavaScript
can anybody provide sample code to read and write into file using javascript?
at present i am trying to read input from json file and display it in textboxes providing the user flexibility to edit the data. Edited data has to be written into json file.

here is the sample html file, i have tested it with firefox working fine.
<!DOCTYPE html>
<html>
<head>
<script>
function handleFileSelect()
{
if (window.File && window.FileReader && window.FileList && window.Blob) {
} else {
alert('The File APIs are not fully supported in this browser.');
return;
}
input = document.getElementById('fileinput');
if (!input) {
alert("Um, couldn't find the fileinput element.");
}
else if (!input.files) {
alert("This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
alert("Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
}
function receivedText() {
//result = fr.result;
document.getElementById('editor').appendChild(document.createTextNode(fr.result))
}
</script>
</head>
<body>
<input type="file" id="fileinput"/>
<input type='button' id='btnLoad' value='Load' onclick='handleFileSelect();'>
<div id="editor"></div>
</body>
</html>

JavaScript running in a web page displayed in a browser cannot access the client file system.
But you can use API's

(No File programming in javascript)
If you mean parsing json in javascript then :-
you can use Douglas crockford JSON lib for parsing:-
JSON.parse method
Refer Link :-
http://www.json.org/js.html
Example,
var abcd= "[{"name" : "sandeep"},{"name" :"Ramesh"}]"
abcd =JSON.parse(abcd);
for (var index=0;index<abcd.length;index++){
alert(abcd[i].name);
}

Related

Set the text file to read in JavaScript?

I am testing out a file reader for one of my html projects. I want the JavaScript program to read a particular file immediately, instead of the file being selected by the user (in this case, me). I have the p tag and the id of the tag as 'file'. When I run the program in my browser (Safari), I get the error message
TypeError: Argument 1 ('blob') to FileReader.readAsText must be an instance of Blob
I have been looking all over the internet to find a solution, but I just can't find anything. I was thinking of doing my program with python and then inserting it into my webpage with trinket.io's iframe tag. But then I sort of gave up on that idea. Here is the code:
var reader = new FileReader();
var fileToRead = "quotes.txt";
// attach event, that will be fired, when read is end
reader.addEventListener("loadend", function() {
document.getElementById('file').innerText = reader.result;
});
reader.readAsText(fileToRead);
I would like the output of this program to show the contents of the text file, yet when I run it in my browser it gives me a blank screen. I hope there is a solution out there.
The FileReader expects a blob - which is a file-like object. It can be a blob stored in the memory or a reference to a file. For security reasons, it doesn't work with file names - you can't simply read an arbitrary file from the user's file system without his consent.
To achieve it with the user's consent, keep reading below.
You'll need the user to use a file input to explicitly select a file. Once a file is selected, the input will trigger an event with a FileList, containing references to the selected files. The file references can then be used in the FileReader to read their contents.
Here's a working example:
fileInput.addEventListener("change", onFileChanged)
function onFileChanged(event) {
const fileList = event.target.files
fileText.value = ""
if (fileList.length === 0) {
console.log("No file selected, please select one!")
return
}
if (fileList.length > 1) {
console.log("Too many files selected, please select only one!")
return
}
// destruct first entry of fileList, equivalent to `const file = fileList[0]`
const [file] = fileList
// you can validate what type of file you accept
if (file.type !== "text/plain") {
console.log("Only text files are supported!")
return
}
console.log("Reading file", file.name)
readFile(file, printText)
}
function readFile(file, callback) {
if (typeof callback !== "function") {
throw new Error("Please supply a callback function to handle the read text!")
}
const reader = new FileReader()
reader.addEventListener("load", function() {
callback(reader.result)
})
return reader.readAsText(file)
}
function printText(text) {
fileText.value = text
}
<input id="fileInput" type="file"/>
<div>
<textarea id="fileText" cols="50" rows="10"></textarea>
</div>

How to read local text file in JavaScript automatically [duplicate]

This question already has answers here:
How to read a local text file in the browser?
(23 answers)
Closed 6 years ago.
I want to read a local text file from my local html file, so I tried to follow the solution in this thread Javascript - read local text file but the suggested solution does not work for me either:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
When I call the function readTextFile("file:///D:/test/text.txt"); no error does show up in firebug but no alert is shown neither. I use Windows und Firefox 51.0.1 (64-Bit).
I don't want to use the function FileReader() in combination with a button <input type='file' onchange='openFile(event)' ... since the text file needs to be read automatically when loading the page. So how can I make work the solution above?
Reading the thread linked it looks like others also have problems with that solution although the thread is marked as solved.
Complete HTML and JavaScript file as an example for reading client side data files. Client side files can only be accessed by the FileReader, specifying a user selected file.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadFile(o)
{
var fr = new FileReader();
fr.onload = function(e)
{
showDataFile(e, o);
};
fr.readAsText(o.files[0]);
}
function showDataFile(e, o)
{
document.getElementById("data").innerText = e.target.result;
}
</script>
</script>
</head>
<body>
Select file to read <input type="file" onchange="loadFile(this)">
<pre id="data"></pre>
</body>
</html>
As a general rule, it's not possible to access the local file system from JavaScript, so your code example shouldn't and couldn't work because of browser security.
However, there's the File and FileReader API which would allow you to read the contents of a file from an <input type="file" /> and is, in reality, your only option for this sort of thing - You could use FileReader.readAsText() to access the files contents. This is a good resource for further information:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
The easiest way to solve my problem is to change the text file to a .js file, save it in the same folder and include it in the html file by <script src="test.js"></script>

How to read local files using HTML 5 FileReader? [duplicate]

This question already has answers here:
Javascript read file without using input
(3 answers)
Closed 6 years ago.
Objective
I am making an application, and I need to read a local file using JavaScript and HTML 5, without any <input> tags or user interaction whatsoever.
What I tried
On my research, I found two tutorials that are heavily cited in SO:
https://www.html5rocks.com/en/tutorials/file/dndfiles/
http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
However, there is a problem. Both of this tutorials require user interaction via the input tag, which is a life killer since I want to read the contents of the file automatically into a string.
Code
So far I managed to get the following code:
let readFile = function(path) {
let reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
console.log(text);
};
// Read in the image file as a data URL.
reader.readAsText(MissingFileHandle);
};
But as you can see, I am missing an important step, I am missing MissingFileHandle. My idea would be to pass a path to this method, and so the method would read the file locally as text and print it into the console, but I am unable to achieve this.
Question
Given a relative path, how can I read the contents of a file using HTML 5 without using <input> tags?
The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.
Is it possible to load a file with JS/HTML5 FileReader on non served page?
How to open a local disk file with Javascript?
How to set a value to a file input in HTML?
Javascript read file without using input
These links help you to find answer.
This Can do a trick.
HTML
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
JS
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}

How to display the content of a local file in browser using java script ( code to be compatible for all browsers)?

I am planning to create a application on my local . I need a javascript code that to render the content from whichever file I am selecting from my system using html file-upload input box. Referred to the below link but
http://www.alecjacobson.com/weblog/?p=1645 where the code is not compatible for other browsers,
Thanks in Advance
For security reasons you can't open a file from the browser. What you can actually do is upload it to the server and then write it back to the page.
To upload the file I suggest you uploadify or jquery upload.
You are welcome.
If you don't care about the cross-browsing support then:
<input id="file" type="file" multiple="" onchange="startRead()">
<pre><code id="output"></code></pre>
function startRead() {
//obtain input element through DOM
var file = document.getElementById('file').files[0];
if (file) {
getAsText(file);
}
}
function getAsText(readFile) {
var reader;
try {
reader = new FileReader();
} catch (e) {
document.getElementById('output').innerHTML = "Error: seems File API is not supported on your browser";
return;
}
// Read file into memory as UTF-8
reader.readAsText(readFile, "UTF-8");
// handle success and errors
reader.onload = loaded;
reader.onerror = errorHandler;
}
function loaded(evt) {
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
function errorHandler(evt) {
if (evt.target.error.code == evt.target.error.NOT_READABLE_ERR) {
// The file could not be read
document.getElementById('output').innerHTML = "Error reading file..."
}
}
We are developing kinds of web-based GUI editor. This issue have been the problem for long time.
As I know, the method in the site you mentioned is the only way. We are using HTML5 File System.
Before this, We've considered using kinds of Flash module, local web server, dropbox, ...

Default file format on upload. jQuery or Javascript

Could you tell me (for example, Google could not), if I can set the default file format for file upload.
Currently it allows to upload all files (please refer to the file image *.*), however I would like to limit to a specific file format.
All help is appreciated.
Environment:
NO HTML5
Backend: Struts
FrontEnd: jQuery-1.6.1
File upload plugin uses iframe to upload files.
you can use this
<input type="file" id="myfile" accept="image/gif, image/jpeg, image/png, image/jpeg" />
but using this. user can anytime change the filter.
additionally you should use
javascript or jquery to validate.
<script type ="text/javascript">
var validFiles=["bmp","gif","png","jpg","jpeg"];//array of allowed extensions
function OnUpload()
{
var obj = document.getElementById("myfile");
var source=obj.value;
var ext=source.substring(source.lastIndexOf(".")+1,source.length).toLowerCase();
for (var i=0; i<validFiles.length; i++)
{
if (validFiles[i]==ext)
break;
}
if (i>=validFiles.length)
{
alert("This not a valid file upload file with an extention of one of the following:\n\n"+validFiles.join(", "));
return false;
}
return true;
}
</script>

Categories