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
    }
}
5
  • See Using Node.js how to read a JSON object Commented Jun 22, 2015 at 2:24
  • You can technically require it now see here. Not sure which is preferred. Commented Jun 22, 2015 at 2:25
  • Your text is not valid JSON. Keys and values must be placed in quote, like: "type": "Object" Commented Jun 22, 2015 at 3:11
  • Looks more like this should be a .js file, and not a .json file ? Commented Jun 22, 2015 at 3: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. Commented Jun 22, 2015 at 3:34

1 Answer 1

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); 
});
Sign up to request clarification or add additional context in comments.

3 Comments

I tried to use the direct require statement but generates an error see above.
You don't have valid JSON, all keys should be quoted with doublequotes and javascript constructors aren't valid values.
@Pindakaas Better you could try jslint to validate your JSON content, correct mistakes and update your JSON file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.