如果JSON不正确,如何验证JSON字符串并返回错误

How to verify JSON string and return error if JSON is not okay

本文关键字:JSON 字符 字符串 返回 错误 验证 串并 不正确 何验证 如果      更新时间:2023-09-26

我正在尝试验证JSON对象是否正常。我有这个服务器,如果JSON正常,它应该能够返回true,如果不正常,则返回错误。我使用curl来提出这样的请求:

curl-D-H'内容类型:application/json'-D'{"name":"user","pass":"uwish"}'http://localhost:8020/register'

在服务器脚本中,控制台日志调用verifyJSON并返回false,但JSON对象是好的。

我想在解析时发现错误(如果JSON不正确)并将其发送到客户端。我试着做到这一点,但我真的不确定自己做了什么。如果有人能帮助我,我将不胜感激。谢谢你抽出时间
这是服务器代码:

var connect = require('connect');
var cors = require('cors');
var http = require('http');
var bodyParser = require('body-parser');
var corsOpts = { origin: '*' };
var app = connect();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cors(corsOpts)).use(function (req, res, next) { 
console.log(req.method);
console.log(req.url);
if(req.url === '/register' && req.method === 'POST')
    register(req,res);
else
    if(req.url === '/ranking' && req.method === 'GET')
        ranking(req, res);
}).listen(8020);
console.log("Server running on 8020");
function register(req , res){
res.setHeader('Content-Type', 'application/json');
var somedata = {}; // return this object if JSON req is okay
console.log(req.body);
console.log(verifyJSON(req.body));
//trying to send the error to the client
if( err = verifyJSON(req.body) ){
    somedata.error = err; // not sure if this is right
    res.end(JSON.stringify(somedata));
}
else
    console.log("do something with this JSON data");
}
function verifyJSON(str){
try {
    JSON.parse(str);
} catch (e) {
    return false;
}
return true;    
}

使用try。。。catch-around解析来检查json输入的有效性,返回实际的错误消息,而不仅仅是true或false。

function verifyJson(input){
   try {
      JSON.parse(input);
   } catch(ex) {
      return ex.message; // Is invalid 
   }
   return false; // Is valid 
}