Parsing a JSON query string into a JSON object

前端 未结 1 1023
终归单人心
终归单人心 2021-01-15 06:04

The query on the API is structured like this:

../myapi/products?_q=genre,retail_price&_a=g,p&p.gt=10&p.lt=20&g.eq=POP

There

相关标签:
1条回答
  • 2021-01-15 06:14

    The first thing is queryStr is not valid JSON. What you have is a string that looks like an object. But you might ask "isn't that JSON?". Short answer: no. Long answer: since JSON is a lightweight data exchange format it has to be readable by a variety of languages (not just Javascript). So quoting keys is a requirement to make this possible:

    var json = '{"foo": true, "bar": 123}';
    var str = '{foo: true, bar: 123}';
    console.log(JSON.parse(json)); // Object {foo: true, bar: 123}
    console.log(JSON.parse(str)); // SyntaxError: Unexpected token f
    

    So, you could stringify the query object to JSON and then parse it before passing it to your mongoose method:

    // On the client
    var queryJSON = JSON.stringify({$and: [{genre: { $eq: 'ROC'}}, {retail_price: {$gt:7}}, {retail_price: {$lt:10}}]});
    // On the server
    var query = JSON.parse(queryJSON); // Object
    

    That said, back to your original two concerns:

    1. Quoted key names: they have zero impact in this regard so they shouldn't be a concern at all.
    2. Incorrect value types: it looks like you already have a procedure for formatting the query to the correct object so you could use Number to coerce the string to a number value. (e.g. Number('10') // 10)
    0 讨论(0)
提交回复
热议问题