Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PostgreSQL中创建嵌套的json blob_Sql_Json_Postgresql - Fatal编程技术网

在PostgreSQL中创建嵌套的json blob

在PostgreSQL中创建嵌套的json blob,sql,json,postgresql,Sql,Json,Postgresql,我试图从如下表中创建嵌套json: +----------+---------+------------------------------+ | unixtime | assetid | data | +----------+---------+------------------------------+ | 10 | 80 | {"inflow": 10, "outflow": 2} | | 20 |

我试图从如下表中创建嵌套json:

+----------+---------+------------------------------+
| unixtime | assetid |             data             |
+----------+---------+------------------------------+
|       10 |      80 | {"inflow": 10, "outflow": 2} |
|       20 |      90 | {"inflow": 10, "outflow": 2} |
|       10 |      80 | {"inflow": 10, "outflow": 2} |
|       20 |      90 | {"inflow": 10, "outflow": 2} |
+----------+---------+------------------------------+
{
    "10": {
        "80": {"inflow": 10, "outflow": 2},
        "90": {"inflow": 10, "outflow": 2}
    },
    "20": {
        "80": {"inflow": 10, "outflow": 2},
        "90": {"inflow": 10, "outflow": 2}
    }
}
然后得到这样的结果:

+----------+---------+------------------------------+
| unixtime | assetid |             data             |
+----------+---------+------------------------------+
|       10 |      80 | {"inflow": 10, "outflow": 2} |
|       20 |      90 | {"inflow": 10, "outflow": 2} |
|       10 |      80 | {"inflow": 10, "outflow": 2} |
|       20 |      90 | {"inflow": 10, "outflow": 2} |
+----------+---------+------------------------------+
{
    "10": {
        "80": {"inflow": 10, "outflow": 2},
        "90": {"inflow": 10, "outflow": 2}
    },
    "20": {
        "80": {"inflow": 10, "outflow": 2},
        "90": {"inflow": 10, "outflow": 2}
    }
}
我尝试过递归地将json数据转换为文本,然后使用json对象将结果转换为json blob,但最终用转义斜杠(\)将json结构搞砸了

任何帮助都将不胜感激

以下是数据链接:


谢谢。

您可以使用
json\u object\u agg()
函数:

....
, m as (
select
    unixdatetime,
    assetid,
    json_object(array_agg(description), array_agg(value::text))
    as value
from input_data
group by unixdatetime, assetid
), j as
(
select json_object_agg("assetid","value") as js,m."unixdatetime"
  from m
 group by "unixdatetime" 
)
select json_object_agg("unixdatetime",js)
  from j

谢谢真不敢相信我花了两个小时在这上面。这看起来比json_对象和数组agg更干净、更快,不是吗?