如何从PostgreSQL的json_to_recordset()函数中获取完整的记录元素?

huangapple go评论63阅读模式
英文:

How to get complete record element from PostgreSQL json_to_recordset() Function?

问题

我想从 json_to_recordset() 中提取完整的记录元素。如何获取它。

以下是我的问题描述:

描述

我有一个带有 JSON 类型的列,其值如下,其中 JSON 数组 的每个元素不一定具有相同的格式。我想将此 JSON 数组转换为表行。

我已尝试使用可用的 json_to_recordset() 函数,我也能够提取单个行的元素,如 idname 等,但无法提取完整的行。

[{"id":"1","type":"user","name":"AV","displayName":"Aviral","Company":"ABC","Age":34},
{"id":"2","type":"user","name":"Ram","displayName":"Ram","City":"Jaipur"}]

我的用例需要将完整的行存储为单列,如何在 PostgreSQL 中实现它。

以下是我为单个字段应用的逻辑

SELECT json_to_recordset( data::json) as r(  id text, name text)

输出 我得到的是:

如何从PostgreSQL的json_to_recordset()函数中获取完整的记录元素?

期望的输出

如何从PostgreSQL的json_to_recordset()函数中获取完整的记录元素?

英文:

I want to extract the complete record elements from json_to_recordset(). How to get it.
Below is the description of my problem statement:

Description

I have one column with JSON Type and with the below value where each element of JSON Array are not necessarily has the same format. I want to convert this JSON Array into Table rows.

I have tried json_to_recordset() function available and I am also able to extract single elements from a row such as an id or name etc but not complete row.

[{"id":"1","type":"user","name":"AV","displayName":"Aviral","Company":"ABC","Age":34},
	{"id":"2","type":"user","name":"Ram","displayName":"Ram","City":"Jaipur"}]

My use case require to store the complete row as a single column how to get it in postgres.

Below logic, I have applied for a single field

SELECT json_to_recordset( data::json) as r(  id text, name text)

The output I am getting:

如何从PostgreSQL的json_to_recordset()函数中获取完整的记录元素?

Expected Output

如何从PostgreSQL的json_to_recordset()函数中获取完整的记录元素?

答案1

得分: 1

你可以使用 json_array_elements 将JSON数组展开为一组JSON值:

->> 用于获取JSON对象字段作为文本

select row->>'id' as id, row->>'name' as name, row
FROM mytable, json_array_elements(myjson) row;

结果:

id	name	row
1	AV	{"id":"1","type":"user","name":"AV","displayName":"Aviral","Company":"ABC","Age":34}
2	Ram	{"id":"2","type":"user","name":"Ram","displayName":"Ram","City":"Jaipur"}

演示在此

英文:

You can do it using json_array_elements to Expands a JSON array to a set of JSON values :

->> to get JSON object field as text

select row->>'id' as id, row->>'name' as name, row
FROM mytable, json_array_elements(myjson) row;

Result :

id	name	row
1	AV	{"id":"1","type":"user","name":"AV","displayName":"Aviral","Company":"ABC","Age":34}
2	Ram	{"id":"2","type":"user","name":"Ram","displayName":"Ram","City":"Jaipur"}

Demo here

huangapple
  • 本文由 发表于 2023年4月10日 19:15:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976592.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定