Developer2012
Developer2012

Reputation: 169

JSON.Parse error - node.js

I'm trying to parse the get param to JSOn with the following code:

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

the value of `req.query.query is:

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

I have tried too:

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

In both I got the error:

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)

Upvotes: 0

Views: 89

Answers (2)

Aaron Dufour
Aaron Dufour

Reputation: 17505

While Muhammad Ali is correct that you can only use double quotes " in valid JSON, there's a bigger issue. Neither ObjectId nor any other sort of function call can occur in valid JSON, so your string is not going to be parsable by any standard function. I suspect that you're going to have to parse it yourself unless you can change the format in which you're receiving the query from the client.

Upvotes: 1

Muhammad Ali
Muhammad Ali

Reputation: 2014

Replace single quote with double quote and double quote with single quote

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

Upvotes: 0

Related Questions