postgres如何迭代嵌套的json对象

klr1opcd  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(411)

我有一个对象如下。我想迭代insert中的每个用户,并将它们插入到我的数据库中。我被困在如何到达内部物体。我有下面这样的代码,我被困在如何进一步进入obejct,它只得到 insert , delete 以及 update . 我用的是postgresql。
我懂了 ->> int Get JSON array element as text '[1,2,3]'::json->>2 在文档中,但不知道如何合并到我的代码中

  1. DECLARE
  2. _key text;
  3. _value text;
  4. BEGIN
  5. FOR _key, _value IN
  6. SELECT * FROM jsonb_each_text($1)
  7. LOOP
  8. RAISE NOTICE '%: %', _key, _value;
  9. END LOOP;
  10. RETURN input;
  11. END
  12. {
  13. insert: {
  14. jsmith:
  15. {
  16. name: 'John Smith',
  17. mail: 'JSmith@smith.com',
  18. jobTitle: 'Lead',
  19. hasImage: true,
  20. teamId: '35'
  21. },
  22. lmark:
  23. {
  24. name: 'Laurendy Mark',
  25. mail: 'LMark@mark.com',
  26. jobTitle: 'System Admin',
  27. hasImage: true,
  28. teamId: '40'
  29. }
  30. },
  31. delete: {
  32. lbeth
  33. {
  34. name: 'Lisa Beth',
  35. mail: 'LBeth@smith.com',
  36. jobTitle: 'Assistant Director',
  37. hasImage: true,
  38. teamId: '40',
  39. uid: '200'
  40. }
  41. },
  42. update: {}
  43. }
ttisahbt

ttisahbt1#

对此,您并不真正需要pl/pgsql函数。这可以使用数据修改cte来完成

  1. with input (col) as (
  2. values ('
  3. {
  4. "insert":{
  5. "jsmith":{"name":"John Smith", "mail":"JSmith@smith.com","jobTitle":"Lead","hasImage":true,"teamId":35},
  6. "lmark":{"name":"Laurendy Mark","mail":"LMark@mark.com","jobTitle":"System Admin","hasImage":true,"teamId":40}
  7. },
  8. "delete":{
  9. "lbeth":{"name":"Lisa Beth","mail":"LBeth@smith.com","jobTitle":"Assistant Director","hasImage":true,"teamId":40,"uid":200}
  10. },
  11. "update":{}
  12. }'::jsonb)
  13. ), do_insert as (
  14. insert into the_table (name, mail, job_title, has_image, team_id)
  15. select i.value ->> 'name',
  16. i.value ->> 'mail',
  17. i.value ->> 'jobTitle',
  18. (i.value ->> 'hasImage')::boolean,
  19. (i.value ->> 'teamId')::int
  20. from input
  21. cross join jsonb_each(col -> 'insert') i
  22. returning *
  23. ), do_delete as (
  24. delete from the_table
  25. where uid in (select (i.value ->> 'uid')::int
  26. from input
  27. cross join jsonb_each(col -> 'delete') i)
  28. )
  29. update the_table
  30. set has_image = (i.value ->> 'hasImage')::boolean
  31. from input
  32. cross join jsonb_each(col -> 'update') i
  33. where (i.value ->> 'uid')::int = the_table.uid
  34. ;

在线示例

展开查看全部

相关问题