pg nodejs 包导致“类型 json 的输入语法无效" [英] pg nodejs package results in 'invalid input syntax for type json'

查看:111
本文介绍了pg nodejs 包导致“类型 json 的输入语法无效"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目有以下设置,使用

简单的表 'tmp' 看起来像这样:

根据 jsonORGpostgres 文档 对象:

{"foo" : true}

是语法上有效的 JSON,当使用 pgAdmin 查询工具时:

UPDATE tmp SET data = '{"foo": false}' WHERE id = '1'

工作正常,但是当我尝试使用 pg 通过快速路由更新我的表时:

router.put('/updateTMP', (req, res) => {//在这种情况下我使用 dummy 而不是 req.body.someKey 用于测试目的让 dummyJSON = {"foo":true};让 dummyID = 1;pg.query(`UPDATE tmp SET data = '${dummyJSON}' WHERE id = '${dummyID}'`, (errUpdate, responseUpdate) => {if (!errUpdate) {//没有错误res.json({success: true, message: responseUpdate});}else {//错误控制台日志(dummyJSON);控制台日志(错误更新);res.json({成功: 假, 消息: errUpdate});}})})

我从数据库中收到以下错误:

 错误:json 类型的输入语法无效

我已经尝试过 postgresql 的 to_json 函数和来自 npm 的 to-json 包 - 都具有相同的负面影响结果.

我是不是缺少一些基本的理解,还是格式/引用问题?

提前感谢您的想法!;)

ps:是的 - 我已经通读了 this那篇..

解决方案

我遇到了同样的问题.尝试使用 JSON.stringify() 将您的 JS 对象转换为字符串,然后再将其传递到查询中,因为 pg 不会总是自动为您执行此操作.

在 GitHub 上查看此问题以了解更多信息信息.

I have following setup for my project, using the pg node-postgres package:

The simple table 'tmp' looks like this:

According to jsonORG and the postgres docs the object:

{"foo" : true}

is syntactically valid JSON, and when using the pgAdmin Query-tool with:

UPDATE tmp SET data = '{"foo": false}' WHERE id = '1'

works fine, but when i try updating my table through my express route using pg:

router.put('/updateTMP', (req, res) => {
    // I use dummies in this case instead of req.body.someKey for testing purposes
    let dummyJSON = {"foo":true};
    let dummyID = 1;
    pg.query(`UPDATE tmp SET data = '${dummyJSON}' WHERE id = '${dummyID}'`, (errUpdate, responseUpdate) => {
        if (!errUpdate) { // NO ERROR
            res.json({success: true, message: responseUpdate});
        }
        else { // ERROR
            console.log(dummyJSON);
            console.log(errUpdate);
            res.json({success: false, message: errUpdate}); 
        }
    })
})

I get the following error from the database:

error: invalid input syntax for type json

I've tried the to_json function from postgresql and the to-json package from npm in the express route - all with the same negative result.

Am i missing some fundamental understanding or is it some formating/quoting-issue?

Thanks in advance for your ideas! ;)

ps: And yes - I've read through this, and that article..

解决方案

I had the same problem. Try converting your JS object to string using JSON.stringify() before passing it into the query as pg won't always do that for you automatically.

See this issue on GitHub for more info.

这篇关于pg nodejs 包导致“类型 json 的输入语法无效"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆