使用单个json列将json文件导入postgres表

时间:2018-04-21 21:31:36

标签: json postgresql import

我一直在尝试将postgres中的json文件作为单个json列加载。

表格: create table book(values json);

该文件如下所示:

[
  {
    "isbn": "846896359-3",
    "title": "Jungle Book 2, The",
    "price": 22.05,
    "date": "12/28/2017",
    "authors": [
      {
        "first": "Marlène",
        "last": "Ashley",
        "age": 38
      },
      {
        "first": "Miléna",
        "last": "Finley",
        "age": 37
      },
      {
        "first": "Stévina",
        "last": "Bullus",
        "age": 44
      }
    ],
    "publisher": {
      "name": "Youspan",
      "address": {
        "street": "Iowa",
        "number": "853",
        "city": "München",
        "country": "Germany"
      },
      "phone": "361-191-8111"
    }
  },
  {
    "isbn": "558973823-7",
    "title": "Star Trek III: The Search for Spock",
    "price": 36.58,
    "date": "4/19/2017",
    "authors": [
      {
        "first": "Uò",
        "last": "Ibel",
        "age": 26
      },
      {
        "first": "Mélys",
        "last": "Grasner",
        "age": 36
      },
      {
        "first": "Mylène",
        "last": "Laven",
        "age": 40
      },
      {
        "first": "Pò",
        "last": "Lapsley",
        "age": 37
      }
    ],
    "publisher": {
      "name": "Chatterbridge",
      "address": {
        "street": "Dennis",
        "number": "1",
        "city": "São Tomé",
        "country": "Sao Tome and Principe"
      },
      "phone": "845-226-0017"
    }
  }
]

尝试了复制命令,但是它引发了'Token "" is invalid.'错误。我也尝试过其他一些解决方案

1 个答案:

答案 0 :(得分:0)

所以,我终于开始工作了。 首先,我使用了从文件中删除了新的行字符 tr -d '\n' < yourfile.txt

然后我运行了以下脚本:

create table Bookstemp(values text);                    

copy Bookstemp from 'BOOKS_DATANew.json';

create table books(valjson json);

Insert into books
select values
from   (
           select json_array_elements(replace(values,'\','\\')::json) as values 
           from   Bookstemp
       ) a;