在javascript中将json对象写入文本文件 [英] Writing a json object to a text file in javascript

查看:1542
本文介绍了在javascript中将json对象写入文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在javascript中有一个JSON对象。我想简单地将JSON对象写入文本文件。从目前为止我遇到的事情表明,由于客户端的安全问题,不可能这样做。有解决方法吗?如果最初放置一些虚拟值,是否可以修改已存在的文件?

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?

谢谢

推荐答案

您可以做的一件事是将JSON设置为即时下载。

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();

工作演示: http ://jsfiddle.net/sLq3F/

除此之外,由于安全原因,您无法在客户端上向文件写入JSON。 (否则您可以访问网站用户的文件系统。)您必须使用服务器端语言,并将文件存储在服务器端。

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.

更正:看起来您可以写入文件,即用户文件系统的沙盒部分。请参阅下面的Kevin Jantzer的评论。

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.

另一个更正:抱歉,Filesystem API未被使用。来自HTMl5Rocks网站:2014年4月,在public-webapps上公布了Filesystem API规范应该被认为是死的。其他浏览器对实现它没有兴趣。

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."

这篇关于在javascript中将json对象写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆