将JSON查询字符串解析为JSON对象

时间:2022-08-26 11:49:44

The query on the API is structured like this:

API上的查询结构如下:

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

There are two arrays: _q which lists the query parameters and _a listing the corresponding aliases. So p -> retail_price and g -> genres

有两个数组:_q列出查询参数,_a列出相应的别名。所以p - > retail_price和g - >流派

I can parse this into:

我可以解析为:

{$and : [ genre: { '$eq': 'POP' }, retail_price: { '$gt': '10' }, retail_price: { '$lt': '20' } ]}

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'

几乎开心。但是这种方法存在一些问题:1。'$ eq'等而不是$ eq等2.数值现在是一个字符串'10'

I consider (2) to be a nasty one. Since the server cannot know the type (maybe it should be '10' instead of 10).

我认为(2)是一个讨厌的人。由于服务器无法知道类型(也许它应该是'10'而不是10)。

So, I want to try another approach. And that is parsing it all into a queryString and then convert that with JSON.parse()

所以,我想尝试另一种方法。那就是将它全部解析为queryString,然后用JSON.parse()转换它

First I put up some query string and try it in the shell:

首先,我提出了一些查询字符串并在shell中尝试:

db.products.find({$and: [{genre: { $eq: 'ROC'}}, {retail_price: {$gt:7}}, {retail_price: {$lt:10}}]})

Works like a charm.

奇迹般有效。

Then I tried this:

然后我尝试了这个:

var queryStr = "{$and: [{genre: { $eq: 'ROC'}}, {retail_price: {$gt:7}}, {retail_price: {$lt:10}}]}";

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.

令我惊讶的是它根本不起作用。

Also doing

console.log(JSON.stringify(JSON.parse(queryStr)));

Does not write output to the console.

不将输出写入控制台。

What is happening here?

这里发生了什么?

1 个解决方案

#1


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:

第一件事是queryStr是无效的JSON。你拥有的是一个看起来像一个对象的字符串。但你可能会问“这不是JSON吗?”。简答:不。答案很长:因为JSON是一种轻量级的数据交换格式,所以它必须能够被各种语言(不仅仅是Javascript)读取。所以引用键是使这成为可能的要求:

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:

因此,您可以将查询对象字符串化为JSON,然后在将其传递给您的mongoose方法之前对其进行解析:

// 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. 引用的关键名称:它们在这方面没有任何影响,所以它们根本不应该成为一个问题。

  3. 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)
  4. 不正确的值类型:看起来您已经有一个将查询格式化为正确对象的过程,因此您可以使用Number将字符串强制转换为数字值。 (例如Number('10')// 10)

#1


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:

第一件事是queryStr是无效的JSON。你拥有的是一个看起来像一个对象的字符串。但你可能会问“这不是JSON吗?”。简答:不。答案很长:因为JSON是一种轻量级的数据交换格式,所以它必须能够被各种语言(不仅仅是Javascript)读取。所以引用键是使这成为可能的要求:

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:

因此,您可以将查询对象字符串化为JSON,然后在将其传递给您的mongoose方法之前对其进行解析:

// 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. 引用的关键名称:它们在这方面没有任何影响,所以它们根本不应该成为一个问题。

  3. 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)
  4. 不正确的值类型:看起来您已经有一个将查询格式化为正确对象的过程,因此您可以使用Number将字符串强制转换为数字值。 (例如Number('10')// 10)