我有以下内容:
路由文件" prontuarios.js":
module.exports = function(app){
getProntuarios = function(request, response, next){
var sqlCustom = request.query;
var connection = app.infra.connectionFactory();
var prontuariosDAO = new app.infra.ProntuariosDAO(connection);
prontuariosDAO.lista(sqlCustom, function(erros, resultados){
if(erros){
return next(erros);
}
response.format({
json: function(){
response.json(resultados);
}
});
});
connection.end();
}
app.route('/v1/prontuarios')
.get(getProntuarios);
...
和DAO文件" ProntuariosDAO.js"
...
ProntuariosDAO.prototype.lista = function(sqlCustom, callback){
var _sqlCustom;
console.log(`sqlCustom ${sqlCustom}`);
if (sqlCustom){
_sqlCustom = sqlCustom;
}
...
当我调用prontuariosDAO.lista
函数时,我希望传递" sqlCustom"参数,但问题是" sqlCustom"必须是函数ProntuariosDAO.prototype.lista
中的JSON对象。但是,它没有发生,sqlCustom参数变得像这样的字符串:
{
limit: '10',
offset: '2',
orderBy: '{"field":"nome","type":"desc"}',
whereAnd:
[
'{"field":"id","operator":"<","value":"300"}',
'{"field":"nome","operator":"like","value":"jo%"}'
]
}
我尝试使用JSON.parse
函数,但它无法正常工作,因为它正在解析orderBy
和whereAnd
,就像字符串一样。
这是一种在JSON中转换该字符串的方法吗?我是否正确传递了HTTP参数?
答案 0 :(得分:0)
看起来你需要递归地应用JSON.parse来获取返回给你的数据:
data = {
limit: '10',
offset: '2',
orderBy: '{"field":"nome","type":"desc"}',
whereAnd:
[
'{"field":"id","operator":"<","value":"300"}',
'{"field":"nome","operator":"like","value":"jo%"}'
]
}
JSON.parse(data.orderBy)