Daniel Wondyifraw
Daniel Wondyifraw

Reputation: 7713

Parsing string json in javascript throws Unexpected token

var filter1 = " { where:{ businessName:{ $like:'%A'} ,'userId': { $gt: 0} }, limit: 1 }"

I want to make pass it like this JSON

  var filter =  { where:{ businessName:{ $like:'%A'} ,'userId': { $gt: 0} }, limit: 1 } 

I did this to make it like JSON example.

JSON.parse(filter)

But it throws the following exception:

SyntaxError: Unexpected token w in JSON at position 3

Upvotes: 0

Views: 66

Answers (2)

Max Koretskyi
Max Koretskyi

Reputation: 105439

It's not valid JSON string. It's more a JavaScript object literal wrapped in quotes.

In JSON standard all keys should be wrapped in quotes, so here is how your JSON would look like:

"{"where":{"businessName":{"$like":"%A"},"userId":{"$gt":0}},"limit":1}"

Since your string is simply a JavaScript object wrapped in quotes, you can arrive at the correct JSON string by simply removing quotes:

var filter1 = { where:{ businessName:{ $like:'%A'} ,'userId': { $gt: 0} }, limit: 1 }

and running it through JSON.stringify:

JSON.stringify(filter1);

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68635

Your JSON is not valid. Use "" with all keys and for values, except numbers and bools

var filter1 = '{ "where": { "businessName" :{ "$like":"%A"} ,"userId": { "$gt": 0} }, "limit": 1 }'

var filter1 = '{ "where": { "businessName" :{ "$like":"%A"} ,"userId": { "$gt": 0} }, "limit": 1 }';

var filter = JSON.parse(filter1);

console.log(filter);

Upvotes: 2

Related Questions