gpt4 book ai didi

json - 在 PostgreSQL 中从 JSON 数组创建 XML

转载 作者:行者123 更新时间:2023-11-29 13:46:41 43 4
gpt4 key购买 nike

我有一个表,其中有一列包含这样的数据:n 个 json 元素的数组

[
{"ref":"3455","desc":"My Product 1","price":"4","quant":"90"},
{"ref":"3455","desc":"My Product 2","price":"5","quant":"80"}
]

我需要解析/迭代每个 JSON 元素。在示例中,我有 2。结果将是一个自定义字符串(实际上是 XML 字符串)。

预期的 XML 结果:

<items>
<item>
<ref>3455</ref>
<desc>My Product 1</desc>
<price>4</price>
<quant>90</quant>
</item>
<item>
<ref>3455</ref>
<desc>My Product 2</desc>
<price>5</price>
<quant>80</quant>
</item>
</items>

实现此目标的最佳方法是什么?

谢谢!

最佳答案

在我的解决方案中,我假设您的 JSON 数组中的对象具有相同的结构。所以我们创建一个 SQL type对于这个对象:

DROP TYPE IF EXISTS item_type;
CREATE TYPE item_type
AS ("ref" int, "desc" VARCHAR(500), price FLOAT, quant INTEGER);
--ref and desc are SQL key words
--so you need to specify that they actually are column names

演示表如下所示:

CREATE TABLE items
(
id SERIAL NOT NULL
CONSTRAINT items_pkey
PRIMARY KEY,
content jsonb DEFAULT '[]'::jsonb NOT NULL
);

查询:

SELECT xmlelement(name items, (--create the root element "items"
SELECT xmlagg(--aggregate "item" elements
xmlelement(NAME item, --create "item" elements
xmlforest(t."ref", t."desc", t.price, t.quant)--create "item" element content
)
)
FROM
(
SELECT (jsonb_populate_recordset(NULL :: item_type, items.content)).*--create records ot of JSON array
FROM items
WHERE items.id = 1 --you can remove where if you want all rows
) AS t
))

解释:
从里到外; (1) 创建我们之前创建的类型的SQL记录(item_type) 使用 jsonb_populate_recordset 从 JSON 数组中提取出来, (2) 创建<item>的内容使用 xmlforest 的节点, (3) 创建<item>元素本身使用 xmlelement , (4) 骨料 <item>元素使用 xmlagg , 创建根元素 <items>使用 xmlelement .

SQLFiddle - 它运行但看起来 SQLFiddle 在输出 XML 结果时有问题所以我将结果转换为 TEXT .

关于json - 在 PostgreSQL 中从 JSON 数组创建 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47179805/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com