繁体   English   中英

如何从嵌套的json到postgresql加载数据?

[英]How to load data from data from nested json to postgresql?

我正在尝试将数据从嵌套 JSON 加载到 PostgreSQL 数据库。

这是来自 json 的示例数据:

{
  "ID":"4654554",
  "Skill_Set" : [ "RN", "React.js", "Node.js", "JS", "D3", "Oracle", "Jenkins", "Spring", "GoogleCloud", "Maven" ],
  "Modified_By" : {
      "name" : "Admin",
      "id" : "545512121"
    },
  "approval" : {
      "first" : false,
      "second" : false,
      "third" : false,
      "all" : false
      }
 }

预期结果是一个具有以下结构的表格:

ID | Skill_SET | Modified_By_name | Modified_By_id | approvel_first | approvel_second
4654554 | "RN", "React.js", "Node.js", "JS", "D3", "Oracle", "Jenkins", "Spring", "GoogleCloud", "Maven" | Admin | 545512121 |  false ...
  • 如何定义列数据类型?

  • 如何将此文件加载到数据库中?

  • PS:*我不需要命令将数据加载到数据库中,我需要了解将“数组”和记录转换为数据库数据类型的方法。

参考: json_array 到 postgresql 数组

create table test_insert_jsonb(id bigint,
            skill_set text[], 
            modified_by jsonb, 
            approval jsonb);

然后写一个function输入是文本,output是插入结果。
将文件加载为文本字符串。 演示

create or replace  function jsonb_insert(p_object text)
returns setof text AS
$body$
    declare
    p_jsonb jsonb; v_rec record;
    v_id bigint;v_Modified_By jsonb;
    v_approval jsonb;v_skill_set text[];
    begin
    p_jsonb := p_object::jsonb;
    if (p_jsonb['ID'] ) is null then raise exception 'no id this function will not work.';
    
    else
        for v_rec in (select * from jsonb_each(p_jsonb))
        loop
            case
            when v_rec.key = 'ID' then v_id := trim( both '"' from (v_rec.value::text));
            when v_rec.key = 'Skill_Set' then
                v_skill_set := jsonb_array_to_text_array(v_rec.value);
            when v_rec.key = 'Modified_By' then v_Modified_By := v_rec.value;
            when v_rec.key = 'approval' then v_approval := v_rec.value;
            else null;
            end case;
        end loop;
        insert into test_insert_jsonb(id, skill_set,modified_by,approval)
                values(v_id,v_skill_set,v_Modified_By, v_approval)
                    returning id into v_id;
        return query
                select row_to_json(e.*)::text from test_insert_jsonb e where id = v_id;
    end if;
    end
$body$
language plpgsql;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM