简体   繁体   English

从Postgres中的嵌套JSON获取值

[英]Get the value from nested JSON in Postgres

I have a table called "Audio" with a column "transcript" as the following: 我有一个名为“ Audio”的表,其列为“ transcript”,如下所示:

{"transcript": [
    {"p": 0, "s": 0, "e": 320, "c": 0.545, "w": "This"}, 
    {"p": 1, "s": 320, "e": 620, "c": 0.825, "w": "call"}, 
    {"p": 2, "s": 620, "e": 780, "c": 0.909, "w": "is"}, 
    {"p": 3, "s": 780, "e": 1010, "c": 0.853, "w": "being"}
    ...
    ]}

I would like to get the value of "p" where "w" matches certain keywords. 我想获取“ p”的值,其中“ w”与某些关键字匹配。

If I do the following query, it will give me the entire 's' entries of Audio where one of its "w" has words "google" or "all." 如果我执行以下查询,它将为我提供音频的整个“ s”条目,其中“ w”之一带有单词“ google”或“ all”。

select json_array_elements(transcript->'transcript')->>'s' 
from Audio, 
   json_array_elements(transcript->'transcript') as temp 
where temp->>'w' ilike any(array['all','google']) 

How could I get only value of "p" where the condition is satisfied? 在满足条件的情况下,如何仅获得“ p”的值?

Edit: How could I get the value of "p" and its corresponding Audio ID at the same time? 编辑:我怎样才能同时获得“ p”的值及其对应的音频ID?

Select your transcript array elements into a common table expression and match from there: 选择您的成绩单数组元素到公共表表达式中,然后从那里进行匹配:

WITH transcript AS (
    SELECT json_array_elements((transcript -> 'transcript')) AS line
    FROM audio
)
SELECT line ->> 'p'
FROM transcript
WHERE line ->> 'w' ILIKE ANY (ARRAY ['all', 'google']);

This will select matching lines from all rows in the audio table. 这将从音频表的所有行中选择匹配的行。 I'm guessing that you'll want to restrict the results to a subset of rows, in which case you'll have to narrow the query. 我猜想您希望将结果限制为行的子集,在这种情况下,您将不得不缩小查询范围。 Assuming an id column, do something like this: 假设有一个id列,请执行以下操作:

WITH transcript AS (
    SELECT
      id,
      json_array_elements((transcript -> 'transcript')) AS line
    FROM audio
    WHERE id = 1
)
SELECT
  id,
  line ->> 'p'
FROM transcript
WHERE line ->> 'w' ILIKE ANY (ARRAY ['call', 'google'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM