使用knex从数据库获取转义斜杠的数据

时间:2019-04-19 04:14:09

标签: node.js json knex.js

我用来从数据库Knex获取数据。接收数据时,请以斜线转义。

返回此:

{"selector":"a[class=\\"xf-product-title__link js-product__title\\"]","site":"https:\\/\\/www.goo.com\\/catalog\\/kartinki\\/nasha/"}

需要:

{"selector":"a[class=\"xf-product-title__link js-product__title\"]","site":"https://www.goo.com/catalog/kartinki/nasha/"}

该如何解决?

我的代码:

let result = new Promise(function (getRes,getErr) {
            knex.from('configs')
            .select('*')
            .where({id:id_config})
                .then((ans) => {
                    getRes(ans);
                }).catch((err) => { getErr(err) })
                .finally(() => {
                    knex.destroy();
                });
        });

        return await result;

1 个答案:

答案 0 :(得分:0)

您正在混合javascript字符串文字表示形式和实际的javascript对象数据以及JSON字符串格式数据:

// store some jsonb data from DB to variable result
> result = null; knex.select(knex.raw(`'{"selector":"a[class=\\"xf-product-title__link js-product__title\\"]","site":"https://www.goo.com/catalog/kartinki/nasha/"}'::jsonb`)).then(res => result = res)

// data was returned from DB as javascript object
> result
[ { jsonb:
     { site: 'https://www.goo.com/catalog/kartinki/nasha/',
       selector: 'a[class="xf-product-title__link js-product__title"]' } } ]

// stringifying data to JSON string requires that " marks are escaped 
// but in javascript string literals \ escape mark shows as \\ because
// otherwise those could be mixed with \t or \n etc.   
> JSON.stringify(result)
'[{"jsonb":{"site":"https://www.goo.com/catalog/kartinki/nasha/","selector":"a[class=\\"xf-product-title__link js-product__title\\"]"}}]'

// however when javascript string literal is printed to console or written
// to file, those \\ marks are outputted as single backslashes
> console.log(JSON.stringify(result))
[{"jsonb":{"site":"https://www.goo.com/catalog/kartinki/nasha/","selector":"a[class=\"xf-product-title__link js-product__title\"]"}}]