danielad danielad - 8 days ago 8
Javascript Question

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

Answer

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);