使用PostgreSQL的json_populate_recordset插入数据时JSON语法错误求助
解决PostgreSQL json_populate_recordset的JSON语法错误
错误原因
PostgreSQL的JSON类型严格遵循RFC 7159标准,要求JSON对象的键必须用双引号包裹。你提供的JSON字符串里的f_name、email等键未加双引号,不符合JSON语法规范,导致解析失败。
修正后的INSERT语句
将JSON对象的键用双引号包裹,同时用单引号包裹整个JSON字符串(内部双引号无需转义):
INSERT INTO users(f_name, email, mobile, username) SELECT f_name, email, mobile, username FROM json_populate_recordset(null::users, '[{"f_name":"Rick","email":"rick@gmail.com", "mobile":"240-454-7845", "username": "rickyC"}]');
额外说明
- 若JSON字符串从外部传入(如应用程序),需确保生成的JSON严格符合标准格式,所有键必须带双引号。
- 也可使用
jsonb_populate_recordset(JSONB类型),语法要求与JSON一致,但性能更优,适合频繁操作JSON数据的场景:
INSERT INTO users(f_name, email, mobile, username) SELECT f_name, email, mobile, username FROM jsonb_populate_recordset(null::users, '[{"f_name":"Rick","email":"rick@gmail.com", "mobile":"240-454-7845", "username": "rickyC"}]');
内容的提问来源于stack exchange,提问作者Timothy Clotworthy
相关产品推荐
相关产品推荐

