在JSON列中每个键将每行扇形化为多行

时间:2014-12-05 18:12:43

标签: json postgresql

我有这张桌子:

CREATE TABLE user_stats (username varchar, metadata_by_topic json);
INSERT INTO user_stats VALUES ('matt', '{"tech":["foo","bar"],"weather":"it is sunny"}');
INSERT INTO user_stats VALUES ('fred', '{"tech":{"stuff":"etc"},"sports":"bruins won"}');

metadata_by_topic中的顶级键始终是字符串(例如" tech"," weather"),但它们下面的值是任意json。我想要一个查询将这些顶级键映射到它们自己的列,并将json值映射到不同的列,如下所示:

username     | topic     | metadata
-----------------------------------
matt         | tech      | ["foo","bar"]
matt         | weather   | "it is sunny"
fred         | tech      | {"stuff":"etc"}
fred         | sports    | "bruins won"

其中,用户名和主题都是VARCHAR类型,元数据是JSON类型。这样:

select * from json_each((select t.metadata_by_topic from user_stats as t));

只有在我添加LIMIT 1内部选择时才有效,但这不是我想要的。

1 个答案:

答案 0 :(得分:1)

更新:这是一个更好的方法

select username, key, metadata_by_topic->key
from
  (select username,  
      json_object_keys(
            (select t.metadata_by_topic from user_stats as t where t.username=us.username)
      ) AS KEY,
      us.metadata_by_topic
    from user_stats us
  ) x