LΞИIИ
LΞИIИ

Reputation: 1454

JSON.parse with functions inside

I have a string that if I turn it into OBJ it works correctly.

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

then I put it in the tagEditor plugin in this way $('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);

but when I do that I get error Uncaught SyntaxError: Unexpected string in JSON at position 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?

Upvotes: 1

Views: 72

Answers (2)

Randy Casburn
Randy Casburn

Reputation: 14175

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. So change it to escaped quotes:

EDIT: to then evaluate the function you must use eval() like this. I have no idea what your intent is for the onChange handler so I modified it so it would actually work:

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>

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371019

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):

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.

Upvotes: 1

Related Questions