在PostgreSQL中基于JSON文件创建表

时间:2014-05-12 12:45:58

标签: json postgresql postgresql-9.1 plpgsql

我收到一些JSON格式的数据。我想将数据存储在数据库(PSQL 9.1)中,但数据结构每天都在变化。

数据示例:

{
"No.":"1",
"Ticker":"A",
"Market Cap":"18468.13",
"P\/E":"25.53",
"Forward P\/E":"16.17",
"PEG":"2.69",
"P\/S":"2.72",
"P\/B":"3.39",
"P\/Cash":"6.74",
"P\/Free Cash Flow":"24.46",
"EPS growth this year":"-35.80%",
"EPS growth next year":"10.91%",
"EPS growth past 5 years":"2.30%",
"EPS growth next 5 years":"9.48%",
"Sales growth past 5 years":"3.30%",
"Price":"55.39",
"Change":"0.16%",
"Volume":"1287900",
"Dividend Yield":"0.96%",
"Return on Assets":"7.00%",
"Return on Equity":"14.20%",
"Return on Investment":"10.20%",
"Current Ratio":"3.30",
"Quick Ratio":"2.60",
"LT Debt\/Equity":"0.50",
"Total Debt\/Equity":"0.50",
"Gross Margin":"52.20%",
"Operating Margin":"15.70%",
"Profit Margin":"10.90%",
"Earnings Date":"5\/14\/2014 4:30:00 PM",
"Company":"Agilent Technologies Inc.",
"Sector":"Healthcare",
"Industry":"Medical Laboratories & Research",
"Country":"USA"
}

我想每天将所有收到的数据存储在新表中。创建具有与收到的JSON相同结构的新表的最简单方法是什么?

1 个答案:

答案 0 :(得分:3)

问题可能来自正则表达式考试。 SQL Fiddle

create or replace function create_table_from_json(json text, tablename text)
returns void language plpgsql
as $$
begin
  execute
    replace(
      replace(
        regexp_replace(
          json,
          '("[^"]*"):("[^"]*")',
          '    \1 text', 'g'),
        '{', 
        format('create table %s (', tablename)),
      '}',
      ');');
end 
$$;

create or replace function insert_from_json(json text, tablename text)
returns void language plpgsql
as $$
begin
  execute
    replace(
      replace(
        regexp_replace(
          json,
          '("[^"]*"):"([^"]*)"',
          '''\2''', 'g'),
        '{', 
        format('insert into %s values (', tablename)),
      '}',
      ');');
end 
$$;