Postgres泛函用于总结json值

时间:2017-09-25 21:20:58

标签: json regex postgresql

我正在开发一个函数来总结调查分数,并且我试图让它变得动态,所以我不必对函数中每个调查的问题数量进行硬编码。答案以JSON格式存储为文本。在这一点上,我循环遍历数据库中的记录,我想我将替换所有以q1,q2,q3,...形式开始的键,并用q替换它们,这样我就可以提取所有值< / p>

temp_answers := regexp_replace(row.answers, 'q[0-9]*', 'q', 'g');

在:

{
  "q5": {
    "text": "StronglyAgree",
    "score": "4"
  },
  "q2": {
    "text": "StronglyAgree",
    "score": "4"
  },
  "q1": {
    "text": "StronglyAgree",
    "score": "4"
  },
  "q4": {
    "text": "StronglyAgree",
    "score": "4"
  },
  "q3": {
    "text": "StronglyAgree",
    "score": "4"
  }
}

在:

{
  "q": {
      "text": "StronglyAgree",
      "score": "4"
  },
  "q": {
      "text": "Disagree",
      "score": "2"
  },
  "q": {
      "text": "StronglyDisagree",
      "score": "1"
  },
  "q": {
      "text": "Agree",
      "score": "3"
  },
  "q": {
      "text": "Agree",
      "score": "3"
  }
}

使用:

temp_answers::json->>'q';

只返回答案集中的一个值。

我真的很想能够使用json功能来获取所有分数,但它看起来像我不能够。 有没有人有任何好的想法或我缺少的功能?

Postgres版本9.4

1 个答案:

答案 0 :(得分:1)

我建议采取不同的方法,将你的json展平到所需的行。

假设quiz表包含id和json answers列:

WITH scores AS (
  SELECT
    q.id, a.key AS question, (a.value ->> 'score')::INT AS score FROM quiz q
    JOIN json_each(q.answers) a ON TRUE 
)
SELECT *
FROM scores;

如果您需要将密钥限制为仅以“q”开头的密钥,请加入ON a.key LIKE 'q%'