2

I have this string (character varying) as a row value in Postgresql :

{'img_0': 'https://random.com/xxxxxx.jpg', 'img_1': 'https://random.com/yyyyyy.jpg', 'img_2': 'https://random.com/zzzzzz.jpg'}

I am trying to json_eact_text() it but can't figure out how to. I have tried to_jsonb() on it (working) and then jsonb_each(), but I have this error :

ERROR:  cannot call jsonb_each on a non-object

My query :

WITH 
test AS (
    SELECT to_jsonb(value) as value FROM attribute_value WHERE id = 43918
)

SELECT jsonb_each(value) FROM test

1 Answer 1

1

Your text value is not valid JSON. JSON requires doublequotes (") to delimit strings.

This will work by doctoring your text provided that your data is consistently wrong:

with t (sometext) as (
  values ($${'img_0': 'https://random.com/xxxxxx.jpg', 'img_1': 'https://random.com/yyyyyy.jpg', 'img_2': 'https://random.com/zzzzzz.jpg'}$$)
)
select jsonb_each_text(replace(sometext, '''', '"')::jsonb)
  from t;

            jsonb_each_text            
---------------------------------------
 (img_0,https://random.com/xxxxxx.jpg)
 (img_1,https://random.com/yyyyyy.jpg)
 (img_2,https://random.com/zzzzzz.jpg)
(3 rows)

To break this out into columns:

with t (sometext) as (
  values ($${'img_0': 'https://random.com/xxxxxx.jpg', 'img_1': 'https://random.com/yyyyyy.jpg', 'img_2': 'https://random.com/zzzzzz.jpg'}$$)
)
select j.*
  from t
 cross join lateral jsonb_each_text(replace(sometext, '''', '"')::jsonb) as j;

  key  |             value             
-------+-------------------------------
 img_0 | https://random.com/xxxxxx.jpg
 img_1 | https://random.com/yyyyyy.jpg
 img_2 | https://random.com/zzzzzz.jpg
(3 rows)
Sign up to request clarification or add additional context in comments.

2 Comments

I had the replace() wrong. Is it possible to have 'img_0' and 'random.com/xxxxxx.jpg' in two different columns ?
@IndiaSke Certainly. Please see the update to the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.