Is it valid to define functions in JSON results?

2018-12-31 18:17发布

Part of a website's JSON response had this (... added for context):

{..., now:function(){return(new Date).getTime()}, ...}

Is adding anonymous functions to JSON valid? I would expect each time you access 'time' to return a different value.

9条回答
爱死公子算了
2楼-- · 2018-12-31 18:47

Function expressions in the JSON are completely possible, just do not forget to wrap it in double quotes. Here is an example taken from noSQL database design:

{
  "_id": "_design/testdb",
  "views": {
    "byName": {
      "map": "function(doc){if(doc.name){emit(doc.name,doc.code)}}"
    }
  }
}

查看更多
春风洒进眼中
3楼-- · 2018-12-31 18:49

It is not standard as far as I know. A quick look at http://json.org/ confirms this.

查看更多
初与友歌
4楼-- · 2018-12-31 18:52

Let's quote one of the spec's - http://tools.ietf.org/html/rfc7159#section-12

The The JavaScript Object Notation (JSON) Data Interchange Format Specification states:

JSON is a subset of JavaScript but excludes assignment and invocation.

Since JSON's syntax is borrowed from JavaScript, it is possible to use that language's "eval()" function to parse JSON texts. This generally constitutes an unacceptable security risk, since the text
could contain executable code along with data declarations
. The same consideration applies to the use of eval()-like functions in any other programming language in which JSON texts conform to that
language's syntax.

So all answers which state, that functions are not part of the JSON standard are correct.

The official answer is: No, it is not valid to define functions in JSON results!


The answer could be yes, because "code is data" and "data is code". Even if JSON is used as a language independent data serialization format, a tunneling of "code" through other types will work.

A JSON string might be used to pass a JS function to the client-side browser for execution.

[{"data":[["1","2"],["3","4"]],"aFunction":"function(){return \"foo bar\";}"}]

This leads to question's like: How to "Execute JavaScript code stored as a string".

Be prepared, to raise your "eval() is evil" flag and stick your "do not tunnel functions through JSON" flag next to it.

查看更多
登录 后发表回答