【问题标题】:Creating XML out of JSON array in PostgreSQL在 PostgreSQL 中从 JSON 数组创建 XML
【发布时间】:2017-11-08 12:29:51
【问题描述】:

我有一个表,其中有一列包含这样的数据: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>

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

谢谢!

【问题讨论】:

  • Edit您的问题并根据您的示例数据添加预期输出。 Formatted textno screen shots.
  • Postgres 中没有专门的工具可以将 json 转换为 xml。我认为这样的转换在客户端应用程序中可能真的很容易。用您喜欢的语言搜索解决方案,例如Convert JSON to XML in Python

标签: json postgresql


【解决方案1】:

在我的解决方案中,我假设 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) 使用 xmlforest 创建 &lt;item&gt; 节点的内容,(3) 使用 xmlelement 创建 &lt;item&gt; 元素本身,(4 ) 使用xmlagg 聚合&lt;item&gt; 元素,使用xmlelement 创建根元素&lt;items&gt;

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

【讨论】:

  • @user3643038 如果对您有帮助,请接受并投票。
猜你喜欢
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 2022-10-19
  • 2018-06-04
  • 2013-01-29
  • 2011-12-26
  • 2016-06-01
  • 1970-01-01
相关资源
最近更新 更多