将JSON查询字符串解析为JSON对象 [英] Parsing a JSON query string into a JSON object
问题描述
关于API的查询的结构如下:
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
有两个数组:_q列出查询参数,_a列出相应的别名.所以p-> retail_price和g->类型
There are two arrays: _q which lists the query parameters and _a listing the corresponding aliases. So p -> retail_price and g -> genres
我可以将其解析为:
{$and : [ genre: { '$eq': 'POP' }, retail_price: { '$gt': '10' }, retail_price: { '$lt': '20' } ]}
快高兴了.但是这种方法存在两个问题: 1.'$ eq'等而不是$ eq等 2.数值现在是字符串'10'
Almost happy. But there are a couple of problems with this approach: 1. the '$eq' etc instead of $eq etc 2. the numeric value is now a string '10'
我认为(2)令人讨厌.由于服务器无法识别类型(也许应该是'10'而不是10).
I consider (2) to be a nasty one. Since the server cannot know the type (maybe it should be '10' instead of 10).
因此,我想尝试另一种方法.并将其全部解析为queryString,然后使用JSON.parse()进行转换
So, I want to try another approach. And that is parsing it all into a queryString and then convert that with JSON.parse()
首先,我放入一些查询字符串并在外壳中尝试它:
First I put up some query string and try it in the shell:
db.products.find({$and: [{genre: { $eq: 'ROC'}}, {retail_price: {$gt:7}}, {retail_price: {$lt:10}}]})
像魅力一样工作.
然后我尝试了此操作
var queryStr = "{$and: [{genre: { $eq: 'ROC'}}, {retail_price: {$gt:7}}, {retail_price: {$lt:10}}]}";
and :(产品是猫鼬模型)
and: (Product is a mongoose model)
Product.find(JSON.parse(queryStr), function(err, product) {
if (err)
res.send(err);
res.json(product);
});
令我惊讶的是,它根本没有用.
To my surprise it did not work at all.
也正在
console.log(JSON.stringify(JSON.parse(queryStr)));
不将输出写入控制台.
Does not write output to the console.
这是怎么回事?
推荐答案
第一件事是queryStr
无效 JSON .您所拥有的是一个看起来像对象的字符串.但是您可能会问不是JSON吗?".简短的回答:不.长答案:由于JSON是一种轻量级的数据交换格式,因此它必须可由多种语言(而不仅仅是Javascript)读取.因此,引号是实现此目的的必要条件:
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
因此,您可以 stringify 将查询对象转换为JSON,然后解析它,然后再将其传递给您的猫鼬方法:
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:
- 引用的键名:它们在这方面的影响为零,因此它们根本不应该成为问题.
- 不正确的值类型:看来您已经有一个将查询格式化为正确对象的过程,因此您可以使用 查看全文