简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM