您可以使用jsonb_populate_record 函数(假设您的json 数据与users 表匹配)。这将强制文本值与用户表的顺序相匹配:
架构 (PostgreSQL v13)
CREATE TABLE users (
userid text,
rolename text,
loginerror int,
email text,
thirdpartyauthenticationkey json
)
查询 #1
WITH d(js) AS (
VALUES
('{"userid":"test", "rolename":"Root", "loginerror":0, "email":"superadmin@ae.com", "thirdpartyauthenticationkey":{}}'::jsonb),
('{"userid":"other", "rolename":"User", "loginerror":324, "email":"nope@ae.com", "thirdpartyauthenticationkey":{}}'::jsonb)
)
SELECT jsonb_populate_record(null::users, js),
jsonb_populate_record(null::users, js)::text AS record_as_text,
pg_typeof(jsonb_populate_record(null::users, js)::text)
FROM d
;
| jsonb_populate_record |
record_as_text |
pg_typeof |
| (test,Root,0,superadmin@ae.com,{}) |
(test,Root,0,superadmin@ae.com,{}) |
text |
| (other,User,324,nope@ae.com,{}) |
(other,User,324,nope@ae.com,{}) |
text |
请注意,如果您正在构建此字符串以将其插入回 postgresql,那么您不需要这样做,因为jsonb_populate_record 的结果将匹配您的表:
查询 #2
WITH d(js) AS (
VALUES
('{"userid":"test", "rolename":"Root", "loginerror":0, "email":"superadmin@ae.com", "thirdpartyauthenticationkey":{}}'::jsonb),
('{"userid":"other", "rolename":"User", "loginerror":324, "email":"nope@ae.com", "thirdpartyauthenticationkey":{}}'::jsonb)
)
INSERT INTO users
SELECT (jsonb_populate_record(null::users, js)).*
FROM d;
没有要显示的结果。
查询 #3
SELECT * FROM users;
| userid |
rolename |
loginerror |
email |
thirdpartyauthenticationkey |
| test |
Root |
0 |
superadmin@ae.com |
[object Object] |
| other |
User |
324 |
nope@ae.com |
[object Object] |
View on DB Fiddle