简体   繁体   中英

node.js require of a json file

I am trying to require() this JSON file.

{
    "info" : function (request) {
        var i = "<pre>";
        i+= "current working directory: " + process.cwd() + "\n";
        i+="request url: " + request.url + "\n";
        i+= "</pre>";
        return i;
    }
}

Using this line

var render = require('./render.json');

But I get an exception from the JSON file of : Unexpected token u

What am I doing wrong please ?

The following works in a browser. Which I would expect, since a function is a object. And nodejs docs suggests JSON can be a module: http://nodejs.org/api/modules.html#modules_file_modules

<html>
<head>
</head>
<body>

<script>

  var a = {
    "b" : function(msg){
      alert(msg);
    }
  }

  a.b("Hello");

</script>

</body>
</html>

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

you cannot have function inside your JSON and use node.

{
    "error": [
        function (request) {

        }
    ]

}

Is it valid to define functions in JSON results?

The way I have gotten around this is to create a js file instead of a json file:
config.js

exports.config = [
    {
        "foo": 12,
        "bar": 10,
        "baz": function(a){
            console.dir(a);
        }
    }
]

then within node:

 config = require('./config.js').config;

 var a = {
   m: 'something',
   o: 'somethingelses'
 }

 config[0].baz(a);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM