JSON.Parse错误 - node.js

时间:2015-03-13 04:17:19

标签: json node.js

我正在尝试使用以下代码将get参数解析为JSOn:

   var query = req.query.query; // 
    query = JSON.parse(query);

`req.query.query的值是:

{'$or': [ { '_id':ObjectId('54ff5ed8d094b1e371fba0a7')}, {'_id':ObjectId('54ffcc00bef7ea3b78d11789')} ]}

我也试过了:

var query = req.query.query; // 
 query = JSON.parse(" {'$or': [ { '_id':ObjectId('54ff5ed8d094b1e371fba0a7')}, {'_id':ObjectId('54ffcc00bef7ea3b78d11789')} ]}");

我都得到了错误:

SyntaxError: Unexpected token '
at Object.parse (native)
at app.get.collectionOcorrencias (/home/ladessa/files/MelhoraCidade/server/app.js:89:23)
at Layer.handle [as handle_request] (/home/ladessa/files/MelhoraCidade/server/node_modules/express/lib/router/layer.js:82:5)
at next (/home/ladessa/files/MelhoraCidade/server/node_modules/express/lib/router/route.js:100:13)
at Route.dispatch (/home/ladessa/files/MelhoraCidade/server/node_modules/express/lib/router/route.js:81:3)
at Layer.handle [as handle_request] (/home/ladessa/files/MelhoraCidade/server/node_modules/express/lib/router/layer.js:82:5)
at /home/ladessa/files/MelhoraCidade/server/node_modules/express/lib/router/index.js:235:24
at Function.proto.process_params (/home/ladessa/files/MelhoraCidade/server/node_modules/express/lib/router/index.js:313:12)
at /home/ladessa/files/MelhoraCidade/server/node_modules/express/lib/router/index.js:229:12
at Function.match_layer (/home/ladessa/files/MelhoraCidade/server/node_modules/express/lib/router/index.js:296:3)

2 个答案:

答案 0 :(得分:1)

虽然Muhammad Ali是正确的,但您只能在有效的JSON中使用双引号",但问题更严重。在有效的JSON中,ObjectId或任何其他类型的函数调用都不会发生,因此任何标准函数都无法解析您的字符串。我怀疑你必须自己解析它,除非你可以改变你从客户端接收查询的格式。

答案 1 :(得分:0)

将双引号替换为单引号,并使用单引号替换双引号

JSON.parse('{"$or": [ { "_id":ObjectId("54ff5ed8d094b1e371fba0a7")}, {"_id":ObjectId("54ffcc00bef7ea3b78d11789")} ]}')