PostgresSQL JSON查询

时间:2018-12-13 23:53:31

标签: json postgresql

我将json存储在具有以下结构的列(oid)中:

{
  "fullName": "test test",
  "personDetails": {
    "address": "Advisor",
    "phoneNumber": "clare.railton@heptonstalls.co.uk"
  },
  "id": "6765788-yt67",
  "submittedDocument": {
    "answers": [
      {
        "questionId": "2",
        "responses": [
          {
            "value": "123456"
          }
        ]
      },
      {
        "questionId": "2.1",
        "responses": [
          {
            "IdA": 1,
            "IdB": 1,
            "value": "false"
          },
          {
            "IdA": 1,
            "IdB": 2,
            "value": "false"
          },
          {
            "IdA": 1,
            "IdB": 3,
            "value": "false"
          },
          {
            "IdA": 1,
            "IdB": 4,
            "value": "true"
          }
        ]
      }
    ]
},
    "date": "2018-11-22",
    "PeriodId": 123456
}

我如何获得所有问题编号的答案值?我已经使用lo_get函数从oid列中获取了json结构,但是我正在努力捕获所需的值。

非常感谢

1 个答案:

答案 0 :(得分:0)

您确定要存储一个大对象来存储json数据吗? Postgres可以处理表中的json列类型:

CREATE TABLE test_json (id INTEGER PRIMARY KEY, json json);
INSERT INTO test_json VALUES(1,'{
  "fullName": "test test",
  "personDetails": {
    "address": "Advisor",
    "phoneNumber": "clare.railton@heptonstalls.co.uk"
  },
  "id": "6765788-yt67",
  "submittedDocument": {
    "answers": [
      {
        "questionId": "2",
        "responses": [
          {
            "value": "123456"
          }
        ]
      },
      {
        "questionId": "2.1",
        "responses": [
          {
            "IdA": 1,
            "IdB": 1,
            "value": "false"
          },
          {
            "IdA": 1,
            "IdB": 2,
            "value": "false"
          },
          {
            "IdA": 1,
            "IdB": 3,
            "value": "false"
          },
          {
            "IdA": 1,
            "IdB": 4,
            "value": "true"
          }
        ]
      }
    ]
},
    "date": "2018-11-22",
    "PeriodId": 123456
}');

SELECT json_extract_path(
json_array_elements(
json_extract_path(
json_array_elements(
json_extract_path((json),'submittedDocument','answers')
),'responses')
),'value'
)FROM test_json;

请参阅:

https://www.postgresql.org/docs/current/functions-json.html