【问题标题】:How to insert nested JSON into PostgreSQL如何将嵌套的 JSON 插入 PostgreSQL
【发布时间】:2022-08-19 14:38:56
【问题描述】:
CREATE TABLE Log (
\"Name\" TEXT,
\"Age\"  TEXT,
\"Country\" TEXT,
\"Numbers\" TEXT
);

SELECT \"Country\", \"Numbers\" 
  FROM json_populate_record( null:: log,
                            \'{
                               \"Name\": \"qazwsx\",
                               \"HostName\": \"Age\",
                               \"Address\": {
                                 \"Country\": \"MNB\",
                                 \"Numbers\": [
                                   {
                                     \"Cell\": 7418520
                                   }
                                 ]
                               }
                             }\');
SELECT * FROM Log

DEMO:响应始终为空。是否有任何其他技巧可以将嵌套的 JSON 插入表中?

  • 您的意思是在您的第一个 SELECT 子句之前有 INSERT INTO log 吗?否则,您不会修改表。
  • 是的,我需要有 INSERT INTO 日志。

标签: sql json postgresql jsonb


【解决方案1】:
CREATE TABLE Log (
    "Name" TEXT,
    "Age"  TEXT,
    "Country" TEXT,
    "Numbers" TEXT
);
insert into Log values('Oslo', '12', 'No', '12');
SELECT json_build_object('Name', 'qazwsx','HostName', "Age", 'Address',
json_build_object(
'Country', 'MNB', 'Numbers', json_build_object('Cell', 7418520)))
FROM Log;

输出:

{"Name" : "qazwsx", "HostName" : "12", "Address" : {"Country" : "MNB", "Numbers" : {"Cell" : 7418520}}}

【讨论】:

    【解决方案2】:

    一个快速而肮脏的例子:

    SELECT
        json_extract_path_text('{"Name": "qazwsx","HostName": "Age","Address": {
    "Country": "MNB", "Numbers": [{"Cell":7418520}]}}'::json, 'Address', 'Country') AS "Country",
        json_extract_path_text('{"Name": "qazwsx","HostName": "Age","Address": {
    "Country": "MNB", "Numbers": [{"Cell":7418520}]}}'::json, 'Address', 'Numbers') AS "Numbers";
    
     Country |      Numbers       
    ---------+--------------------
     "MNB"   | [{"Cell":7418520}]
    
    
    

    使用来自她JSON functions 的 JSON 路径语言的更好的版本9.16.2。 SQL/JSON 路径语言

    SELECT
        t[0] AS "Country",
        t[1] AS "Numbers"
    FROM
        jsonb_path_query_array('{"Name": "qazwsx","HostName": "Age","Address": {
    "Country": "MNB", "Numbers": [{"Cell":7418520}]}}'::jsonb, '$.Address.*') AS t;
    
     Country |       Numbers       
    ---------+---------------------
     "MNB"   | [{"Cell": 7418520}]
    

    尽管上述内容确实取决于Address 对象中的顺序保持不变。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2019-12-02
      • 2018-06-19
      • 2019-04-24
      相关资源
      最近更新 更多