如何从PostgreSQL中的JSON字符串中根据键检索值。

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

How to retrieve value based on Key from JSON string in PosgresSql

问题

Here is the translated content without code:

在处理存储在数据库表列中的JSON字符串时:

假设表名为t1,列名为data:

数据列存储JSON字符串如下:

[{"K":"V"}]

以下是我根据键获取值的查询:

从json_array_elements(select data from t1) Key中选择Value ->> 'Value'
其中Key->>'Key'='K';

执行时,它给我语法错误。

尝试了所有可能的方法来修复这个问题,最终需要帮助。

----编辑这是我如何获得所需结果的方式------

  1. 创建一个表:

    创建表t1 (
    id int,
    data json
    );

  2. 将数据插入t1表:

    插入到t1中的值

    (1,'[{"K":"V"}]'),
    (2,'[{"loadShortCut_AutoText":"both"}]'),
    (3,'[{"P":"R"}]');

  3. 以下查询以获得输出:

    选择行, row->>'loadShortCut_AutoText' as value
    从t1, json_array_elements (t1.data) as row中
    其中t1.id=2;

  4. 输出:

    {"loadShortCut_AutoText":"both"} both

英文:

While working on JSON string which is stored in a DB table column as:

lets say table name is t1 and column name is data:

data column stores json string as:

[{"K":"V"}]

Below is my query to get the Value based on Key:

select Value ->> 'Value'
from json_array_elements(select data from t1) Key
where Key->>'Key'='K';

on execution, it gives me syntax error.

Tried all the possible way to fix this but finally need help.

----Edit This is how I got the required result------

  1. create a table:

    CREATE TABLE t1 (
    id int,
    data json
    );

  2. Insert data into t1 table:

insert into t1 values

(1,'[{"K":"V"}]'),
(2,'[{"loadShortCut_AutoText":"both"}]'),
(3,'[{"P":"R"}]');
  1. Below query to get the output:

    select row, row->>'loadShortCut_AutoText' as value
    from t1, json_array_elements (t1.data) as row
    WHERE t1.id=2;

  2. Output:

    {"loadShortCut_AutoText":"both"} both

答案1

得分: 1

你可以尝试这样做:

选择 row->>'K' 作为 value
从 t1, json_array_elements (data) 作为 row
WHERE row->>'K' 不为空

只有当键 'K' 存在时才会返回数据。

英文:

You can Try this :

select row->>'K' as value
from t1, json_array_elements (data) as row
WHERE row->>'K' is not null

This will return data only if the key 'K' exists

Demo here

答案2

得分: 0

json_array_elements() 返回每个数组元素的一行,而这个元素本身是一个 JSON 值。要访问该元素中的值,您需要使用 ->> 'K'

select 语句不能作为参数传递。您需要将源表放入 "main" FROM 子句中:

select e.item ->> 'K' as value
from t1 
   cross join json_array_elements(t1.data) as e(item)
英文:

json_array_elements() returns one row per array element which again is a JSON value. To access the value from that element you need to use ->> 'K'

A select statement can not be passed as a parameter. You need to put the source table into the "main" FROM clause:

select e.item ->> 'K' as value
from t1 
   cross join json_array_elements(t1.data) as e(item)

答案3

得分: 0

你可以使用jsonb_path_query_array来直接查询JSON数组(需要将json列转换为jsonb)。

select
id, data,
(jsonb_path_query_array(t1.data::jsonb, '$[*]?(exists (@."K"))'::jsonpath) -> 0) #>> '{K}'::text[] AS k_value
from t1

JSON路径$[*]?(exists (@."K"))选取包含键"K"的所有数组元素,然后使用-> 0选取第一个元素,并提取其值#>> '{K}'::text[]

这种方法的优点是,它也适用于具有重复数据(id=4)和null值(id=6)的JSON数组,如示例输出所示。

id|data                   |k_value|
--+-----------------------+-------+
 1|[{\"K\":\"V\"}]            |V      |
 2|[{\"K\":\"V\"},{\"A\":\"B\"}]  |V      |
 3|[{\"Z\":\"V\"},{\"A\":\"B\"}]  |       |
 4|[{\"K\":\"V\"},{\"K\":\"B\"}]  |V      |
 5|[{\"Z\":\"V\"},{\"K\":\"B\"}]  |B      |
 6|[{\"Z\":\"V\"},{\"K\": null}]|       |
英文:

Alternatively you may use jsonb_path_query_array to query direct the json array (cast of the json column to jsonb is required)

select
id, data,
(jsonb_path_query_array(t1.data::jsonb, '$[*]?(exists (@."K"))'::jsonpath) -> 0) #>> '{K}'::text[] AS k_value
from t1

The JSON path $[*]?(exists (@."K")) select all array element that contains the key "K" than takes the first such -> 0 and extracts the value of it #>> '{K}'::text[].

The advantage of this approach is that it works also for JSON arrays with duplicit data (id=4) and null values (id=6) as illustrated on the sample output

id|data                   |k_value|
--+-----------------------+-------+
 1|[{"K":"V"}]            |V      |
 2|[{"K":"V"},{"A":"B"}]  |V      |
 3|[{"Z":"V"},{"A":"B"}]  |       |
 4|[{"K":"V"},{"K":"B"}]  |V      |
 5|[{"Z":"V"},{"K":"B"}]  |B      |
 6|[{"Z":"V"},{"K": null}]|       |

huangapple
  • 本文由 发表于 2023年4月13日 21:29:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76006030.html
匿名

发表评论

匿名网友

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

确定