Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

Writing a json object to a text file in javascript

I have a JSON object in javascript. I want to simply write the JSON object to a text file. From the things that I came across so far indicate that it is not possible to do so because of security concerns on the client side. Is there a workaround?. Will it be possible to modify a file already present if put some dummy values initially?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One thing you can do is setup the JSON as a download on the fly.

var data = "{name: 'Bob', occupation: 'Plumber'}";
var url = 'data:text/json;charset=utf8,' + encodeURIComponent(data);
window.open(url, '_blank');
window.focus();

Working demo: http://jsfiddle.net/sLq3F/

Apart from that, you can't write a JSON to a file on the clientside due to security reasons. (Otherwise you have access to the filesystems of your website's users.) You would have to use a server-side language for this, and store the file on the server-side.


Correction: Looks like you can write to a file, i.e., a "sandboxed section" of the user's filesystem. See Kevin Jantzer's comment below.

Another Correction: Sorry, the Filesystem API isn't in use. From the HTMl5Rocks website: "In April 2014, it was announced on public-webapps that the Filesystem API spec should be considered dead. Other browsers have showed little interest in implementing it."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...