在 Postgres 9.4 中将 json_to_record 与 JSON 数组元素一起使用时出现“错误:格式错误的数组文字”

Tay*_*tay 9 postgresql json postgresql-9.4

这很好地说明了这个问题:

当 b 列是文本类型而不是数组时,以下工作:

select * 
from json_to_record('{"a":1,"b":["hello", "There"],"c":"bar"}') 
    as x(a int, b text, d text);

 a |         b          | d
---+--------------------+---
 1 | ["hello", "There"] |
Run Code Online (Sandbox Code Playgroud)

但是,如果我将该b列定义为数组,则会出现此错误:

select * 
from json_to_record('{"a":1,"b":["hello", "There"],"c":"bar"}') 
    as x(a int, b text[], d text)

ERROR:  malformed array literal: "["hello", "There"]"
DETAIL:  "[" must introduce explicitly-specified array dimensions.
Run Code Online (Sandbox Code Playgroud)

如何说服/强制json_to_record(或json_populate_record)将 JSON 数组转换为目标列类型的 Postgres 数组?

dez*_*zso 7

对克里斯的回答略有不同:

SELECT a, translate(b, '[]', '{}')::text[] AS b, d
FROM json_to_record('{"a": 1, "b": ["hello", "There"], "c": "bar"}')
AS x(a int, b text, d text);
Run Code Online (Sandbox Code Playgroud)

想法是一样的:将 JSON 数组转换为数组 - 在这种情况下,通过数组文字。除了看起来更简洁的代码(虽然我喜欢它,正则表达式通常在这方面没有太大帮助:),它似乎也稍微快了一点:

CREATE TABLE jsonb_test (
    id serial,
    data jsonb
);

INSERT INTO jsonb_test (id, data)
SELECT i, format('{"a": %s, "b": ["foo", "bar"], "c": "baz"}', i::text)::jsonb 
FROM generate_series(1,10000) t(i);

SELECT a, string_to_array(regexp_replace(b, '\[*\"*\s*\]*','','g'),',') AS b, d
FROM jsonb_test AS j, 
LATERAL json_to_record(j.data::json) AS r(a int, b text, d text);

-- versus 

SELECT a, translate(b, '[]', '{}')::text[] AS b, d
FROM jsonb_test AS j, 
LATERAL json_to_record(j.data::json) AS r(a int, b text, d text);
Run Code Online (Sandbox Code Playgroud)

在这个数据集和我的测试盒上,正则表达式版本显示平均执行时间为300 ms,而我的版本显示为210 ms


Chr*_*ris 1

这可能不是最优雅的解决方案,但它会解决您的问题......

SELECT a,string_to_array(regexp_replace(b, '\[*\"*\s*\]*','','g'),',') AS b,d
FROM json_to_record('{"a":1,"b":["hello", "There"],"c":"bar"}')
AS x(a int, b text, d text);
Run Code Online (Sandbox Code Playgroud)

它的工作原理非常简单:

首先,获取text中的字符串b,并将其剥离为有用的信息。这是通过使用regexp_replace()as来完成的

regexp_replace(b, '\[*\"*\s*\]*','','g')
Run Code Online (Sandbox Code Playgroud)

删除["]和任何空白字符的所有实例,或者更具体地说,将这些字符的任何实例替换为'',并全局应用它,通过使用标志 来表示'g'

接下来string_to_array(),只需使用as将字符串拆分为数组

string_to_array(your_string,',')
Run Code Online (Sandbox Code Playgroud)

在这种情况下your_string,只是上面的结果regexp_replace()。第二个参数','表明string_to_array()项目以逗号分隔。

这将产生一个text[]包含您所需条目的字段。