简体   繁体   中英

How do I select a value in a key:value pair within a list in a column using SQL?

In a table called payouts, there is a column stripeResponseData where the data is in the following structure:

{"id":"tr_1BlSHbGQXLV7RqqnHJffUVO0","object":"transfer","amount":39415,"amount_reversed":0,"balance_transaction":"txn_1BlSHbGQXfV7AqqnGi2o7UiY","created":1516239215,"currency":"usd","description":null,"destination":"acct_1BWWAmAzms5xPfV9","destination_payment":"py_1BlSHbAzms5xkfV91RHAOrno","livemode":true,"metadata":{},"reversals":{"object":"list","data":[],"has_more":false,"total_count":0,"url":"/v1/transfers/tr_1BlSHbYQXLV7AqqnHJffUVO0/reversals"},"reversed":false,"source_transaction":null,"source_type":"card","transfer_group":null}

Within my SQL SELECT statement, I want to return only the value of the key "destination". How do I write my SQL query?

My desired result of the query:

SELECT "stripeResponseData" FROM payouts [...]

(where I don't know how to write [...]) should look like the following (assume we have 3 rows with different values on "destination"):

acct_1BWWAmAzms5xPfV9

acct_1AY0phDc9pCDpLR8

acct_1AwG3VL7DXxftOaS

How do I extract that value from the list within the stripeResponseData column?

See this sqlfiddle . This query will fetch the ID from stripResponseData where the id is a specific id (Probably not very useful, but does show you how to select and query):

SELECT data->>'id' FROM stripeResponseData WHERE data @> '{"id":"tr_1BlSHbGQXLV7RqqnHJffUVO0"}';

Because you mentioned your data was a string, you need to to type conversions to query/use it correctly. See this sqlfiddle :

SELECT data::jsonb->>'id' FROM stripeResponseData WHERE data::jsonb @> '{"id":"tr_1BlSHbGQXLV7RqqnHJffUVO0"}';

Per your edit, you can simply query destination in almost the exact same way. This will get all the id's from stripeResponseData where destination = acct_1BWWAmAzms5xPfV9 :

SELECT data::jsonb->>'id' FROM stripeResponseData WHERE data::jsonb @> '{"destination":"acct_1BWWAmAzms5xPfV9"}';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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