[英]What is the right way to store JavaScript source code in a json object?
I want to edit JavaScript in a textarea and store it back into a JavaScript object. 我想在文本区域中编辑JavaScript并将其存储回JavaScript对象中。 For example I have this object:
例如,我有这个对象:
var item1 = {
'id' : 1,
'title':'title',
'sourcecode' : "alert('hallo')"
};
If I would change the content to alert("hallo")
or a even more complex example does this break my object? 如果我将内容更改为
alert("hallo")
或更复杂的示例,是否会破坏我的对象?
I would think there is some escape function like this https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/escape . 我认为这里有一些转义功能,例如https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/escape 。 But it is marked as deprecated.
但是它被标记为已弃用。
So if this is deprecated what would be the right way for storing complex JavaScript code into a JavaScript object? 因此,如果不赞成这样做,将复杂的JavaScript代码存储到JavaScript对象中的正确方法是什么?
Should I use stringify ? 我应该使用stringify吗?
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
JSON.stringify()方法将JavaScript值转换为JSON字符串,如果指定了replacer函数,则可以选择替换值,如果指定了replacer数组,则可以仅包括指定的属性。
This does not read like there is an automated escape build in. 这看起来不像是内置了自动转义符。
If you need to send the data to a server, I'd say you should encodeURI
your sourceCode, and then JSON.stringify the entire object. 如果您需要将数据发送到服务器,我说你应该
encodeURI
你的源代码,然后JSON.stringify整个对象。 When retreiving data from the server, you should decodeURI
the sourceCode 当从服务器retreiving数据,你应该
decodeURI
的源代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.