0

I have an object, example:

var object = { name: "lalala", alert: function(){ alert(this.name)} }

I want send this to my server (nodejs+express) as a JSON, but I am getting this parser error, how I can do this?

JSON example:

{ "name": "lalala", "alert": "function"(){ "alert"("this.name") } }
Lix
  • 47,311
  • 12
  • 103
  • 131
siavolt
  • 6,869
  • 5
  • 24
  • 27

4 Answers4

0

What you have there is not a valid JSON object. You can't have a function inside of a JSON. You are working with a JavaScript Object instead. Take a look at the JSON spec to learn exactly what is valid for JSON.


If you really wanted to pass that data to your server, you would have to convert the value to a string and then eval (shudder) it at a later stage to get back the underlying function.

Lix
  • 47,311
  • 12
  • 103
  • 131
0

This totally odd and not proper way of doing a JSON

You can't have a function inside a JSON object,

That why you got parser error...

Anto king
  • 1,222
  • 1
  • 13
  • 26
0

Don't do it that way. Send the value of the alert in the json, and then run the alert function when the value is received at the other end.

var object = { name: "lalala", alert: "lalala"}

alert(object.alert);

Edit: In fact all you would need is

var object = { name: "lalala"}

When response received:

alert(object.name);
Dan Brown
  • 1,515
  • 1
  • 9
  • 13
0

You could use the following trick.

var c = { "s" : "sss", "alert" : "alert(c.s)"}
eval(c.alert);

You will get your alert. However it's not going to fly with something like:

eval("function(){alert(c.s);}")
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265