简体   繁体   中英

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

I would think there is some escape function like this 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?

Should I use 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.

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. When retreiving data from the server, you should decodeURI the sourceCode

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM