简体   繁体   English

如何在Postgresql 9.2中使用JSON插入数据

[英]How to insert data by using json in postgresql 9.2

I have two tables called book and author . 我有两个表,分别称为bookauthor

create table book(bookid BIGSERIAL,
           bookname VARCHAR,
           book_type VARCHAR,
           book_pub_date DATE
           );

create table Author(Authorid BIGSERIAL,
           Authorname VARCHAR,
           Author_emailadddr VARCHAR,
           Author_phone integer
           );

Application will pass the data in JSON format thru stored function. 应用程序将通过存储函数传递JSON格式的数据。 So how to store the JSON data into a tables? 那么如何将JSON数据存储到表中呢?

Input data (Application will pass the following data thru stored function): 输入数据(应用程序将通过存储的函数传递以下数据):

{
    "bookid" : "1",
    "bookname" : "sample book",
    "book type" : "history",
    "book_pub_date" : "2015-09-08",
    "Author" : [{
            "Authorname" : "xyz",
            "Author_emailadddr" : "xyz@gmail.com",
            "Author_phone" : "080-99978754"
        }
    ]
}

Is it possible to parse the json data into a tables? 是否可以将json数据解析为表?

(I'm using PostgreSQL 9.2). (我使用的是PostgreSQL 9.2)。

I think you might need Postgres 9.3+ for a pure sql solution. 我认为您可能需要Postgres 9.3+才能获得纯SQL解决方案。 9.2 has limited json functionality compared to newer versions. 与较新版本相比,9.2具有有限的json功能。 http://www.postgresql.org/docs/9.2/static/functions-json.html http://www.postgresql.org/docs/9.2/static/functions-json.html

In PostgreSQL 9.2 you will need to use a function written with pl/perl, pl/python, etc, using the relevant JSON decoding support for that language, and using the SPI to then insert the extracted data into tables. 在PostgreSQL 9.2中,您将需要使用用pl / perl,pl / python等编写的函数,使用对该语言的相关JSON解码支持,然后使用SPI将提取的数据插入表中。 Use, eg Python's json module or Perl's JSON module to extract the fields, then the relevant SPI calls to create SQL to do the inserts based on the extracted data. 使用例如Python的json模块或Perl的JSON模块提取字段,然后使用相关的SPI调用创建SQL以根据提取的数据进行插入。

See: 看到:

In particular, note the sections of the plperl and plpython docs for interacting with the database and running queries. 特别是,请注意plperl和plpython文档中与数据库进行交互并运行查询的部分。

It's really not much different to doing it with an external script. 与使用外部脚本进行的操作实际上并没有太大区别。


In PostgreSQL 9.4 and above you could start to use PostgreSQL's own json support to extract parts of the json in pl/pgsql and insert the extracted sections. 在PostgreSQL 9.4及更高版本中,您可以开始使用PostgreSQL自己的json支持在pl / pgsql中提取json的一部分并insert提取的部分。 No more need for plperl or plpython. 不再需要plperl或plpython。

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

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