1

I have a simple node.js service where I perform some json validation against a schema defined in jsonSchema. The service looks like:

app.post('/*', function (req, res) {
        var isvalid = require('isvalid');
        var validJson=true;
        var schema = require('./schema.json')
        isvalid(req.body,schema
            , function(err, validObj) {
                if (!validObj) {
                    validJson = false;
                }
                handleRequest(validJson,res,err,req);
            });
})

Trying to use the direct require statement in the 4th line above. This generates an error:

SyntaxError: c:\heroku\nodejs_paperwork\schema.json: Unexpected token t

This is my schema.json:

{
  type: Object,
  "schema": {
    "totalRecords": {
      type: String
    },
    "skip": {
      type: Number
    },
    "take": {
      type: Number
    }
}
Pindakaas
  • 4,389
  • 16
  • 48
  • 83
  • See [Using Node.js how to read a JSON object](http://stackoverflow.com/questions/10011011/using-node-js-how-do-i-read-a-json-object-into-server-memory) – Carpetfizz Jun 22 '15 at 02:24
  • You can technically require it now see [here](http://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js). Not sure which is preferred. – aug Jun 22 '15 at 02:25
  • Your text is not valid JSON. Keys and values must be placed in quote, like: `"type": "Object"` – long.luc Jun 22 '15 at 03:11
  • Looks more like this should be a `.js` file, and not a `.json` file ? – adeneo Jun 22 '15 at 03:12
  • ok noted it is not json but I would still like to read the filecontents to use for my validation. The require statement throws an error. – Pindakaas Jun 22 '15 at 03:34

1 Answers1

1

You may have overlooked. You can just load and parse it with require statement.

var jsonData = require('/path/to/yourfile.json');

However, the output from the method above is cached, once you update your JSON file and load it with require again, it loads the content from cache. If your JSON file which stores the schema does not change so often, this method might be useful.

If you want to load your JSON file from disk every time, not from cache. Use fs:

var fs = require('fs');

fs.readFile(filepath, 'utf8', function (err, data) {
  if (err) {
    // handle error
    return;
  }

  jsonData = JSON.parse(data); 
});
TaoPR
  • 5,932
  • 3
  • 25
  • 35
  • I tried to use the direct require statement but generates an error see above. – Pindakaas Jun 22 '15 at 03:05
  • 2
    You don't have valid JSON, all keys should be quoted with doublequotes and javascript constructors aren't valid values. – adeneo Jun 22 '15 at 03:10
  • @Pindakaas Better you could try jslint to validate your JSON content, correct mistakes and update your JSON file. – TaoPR Jun 22 '15 at 03:25