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") } }
2
  • You can't send a funtion as value in json Commented Jul 24, 2014 at 15:47
  • That won't be valid json. The best thing you could do is to put your function in a string and evaluate that, but it isn't something your really should be doing. Commented Jul 24, 2014 at 15:48

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

1 Comment

Is this will really works?
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);}")

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.