Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to define functions in JSON results?

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.

like image 792
Zachary Scott Avatar asked Jan 04 '10 19:01

Zachary Scott


2 Answers

No.

JSON is purely meant to be a data description language. As noted on http://www.json.org, it is a "lightweight data-interchange format." - not a programming language.

Per http://en.wikipedia.org/wiki/JSON, the "basic types" supported are:

  • Number (integer, real, or floating point)
  • String (double-quoted Unicode with backslash escaping)
  • Boolean (true and false)
  • Array (an ordered sequence of values, comma-separated and enclosed in square brackets)
  • Object (collection of key:value pairs, comma-separated and enclosed in curly braces)
  • null
like image 169
Mike Avatar answered Sep 29 '22 21:09

Mike


The problem is that JSON as a data definition language evolved out of JSON as a JavaScript Object Notation. Since Javascript supports eval on JSON, it is legitimate to put JSON code inside JSON (in that use-case). If you're using JSON to pass data remotely, then I would say it is bad practice to put methods in the JSON because you may not have modeled your client-server interaction well. And, further, when wishing to use JSON as a data description language I would say you could get yourself into trouble by embedding methods because some JSON parsers were written with only data description in mind and may not support method definitions in the structure.

Wikipedia JSON entry makes a good case for not including methods in JSON, citing security concerns:

Unless you absolutely trust the source of the text, and you have a need to parse and accept text that is not strictly JSON compliant, you should avoid eval() and use JSON.parse() or another JSON specific parser instead. A JSON parser will recognize only JSON text and will reject other text, which could contain malevolent JavaScript. In browsers that provide native JSON support, JSON parsers are also much faster than eval. It is expected that native JSON support will be included in the next ECMAScript standard.

like image 44
harschware Avatar answered Sep 29 '22 23:09

harschware