简体   繁体   English

JSON.parse具有内部函数

[英]JSON.parse with functions inside

I have a string that if I turn it into OBJ it works correctly. 我有一个字符串,如果将其转换为OBJ,它将正常工作。

var obj = JSON.parse('{ "placeholder": "Hello...."} ');

then I put it in the tagEditor plugin in this way $('textarea').tagEditor(obj); 然后我以这种方式将其放入tagEditor插件$('textarea').tagEditor(obj);

But I also need to evaluate within if there is a function and that it works, in this way. 但是我还需要以这种方式评估内部是否有功能以及该功能是否有效。

var obj = JSON.parse('{ "placeholder": "Hello....", "onChange":"function(a,b,c)}{ }"} ');

and I put it....... $('textarea').tagEditor(obj); 然后我放上它。...... $('textarea').tagEditor(obj);

but when I do that I get error Uncaught SyntaxError: Unexpected string in JSON at position 38 但是当我这样做时,我收到错误Uncaught SyntaxError:JSON中意外的字符串在位置38

Actually I want to evaluate the function that is by string, As you can see when I put the event "onchange" and the function within the object this has to evaluate it for the plugin to work Does anyone know how to solve that problem? 实际上,我想评估字符串形式的函数,正如您看到的那样,当我将事件“ onchange”和对象中的函数放入该对象中时,必须对其进行评估才能使插件正常工作。有人知道如何解决该问题吗?

You should first declare the function, then call toString on the function (which will automatically escape the ' s, which is the problem in your current syntax): 您应该首先声明该函数,然后在该函数上调用toString (这将自动转义' ,这是当前语法中的问题):

 function x(a, b, c){ return ''; } const stringified = JSON.stringify({ placeholder: "Hello....", onChange: x.toString() }); 

Specifically, because the string delimiters for the function property value use ' , you need to escape the ' s used inside. 具体而言,因为对于功能属性值使用字符串分隔符'你需要逃脱'内部使用秒。 (turn (转

"onChange":"function(a,b,c)}{ return ''; }"

into

"onChange":"function(a,b,c)}{ return \'\'; }"

)

But I wouldn't recommend doing that manually, it'll be pretty tedious and somewhat error-prone - the toString() method is probably a better option. 但我不建议手动执行此操作,这将非常乏味且容易出错toString()方法可能是一个更好的选择。

The syntax is invalid: 语法无效:

var obj = JSON.parse('{ "placeholder": "Hello....", "onChange":"function(a,b,c)}{ return ''; }"} ');

You JSON is quoted properly, but you preempted the single quotes inside the function declaration. 您的JSON被正确地引用了,但是您抢占了函数声明中的单引号。 So change it to escaped quotes: 因此,将其更改为转义引号:

EDIT: to then evaluate the function you must use eval() like this. 编辑:然后评估函数,您必须使用eval()这样。 I have no idea what your intent is for the onChange handler so I modified it so it would actually work: 我不知道您对onChange处理程序的意图是什么,所以我对其进行了修改,使其实际上可以工作:

 var obj = JSON.parse('{ "placeholder": "Hello....", "onChange":"function handler(e){ console.log(e.target.value); }"} '); console.log(obj); eval(obj.onChange); document.querySelector('input').onchange = handler; 
 <input> <div></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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