Skip to content

Instantly share code, notes, and snippets.

@yuki-takeichi
Last active October 15, 2015 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yuki-takeichi/c4812f7af46f7f84e958 to your computer and use it in GitHub Desktop.
Save yuki-takeichi/c4812f7af46f7f84e958 to your computer and use it in GitHub Desktop.
Recursive JSON object traversal by PostgreSQL
{"car":"H","cdr":{"car":"e","cdr":{"car":"l","cdr":{"car":"l","cdr":{"car":"o","cdr":{"car":" ","cdr":{"car":"w","cdr":{"car":"o","cdr":{"car":"r","cdr":{"car":"l","cdr":{"car":"d","cdr":{"car":"!","cdr":{}}}}}}}}}}}}}
drop table lisp;
create table lisp (
obj jsonb
);
copy lisp
from '/lisp.json'
with csv quote e'\x01' delimiter e'\x02'
;
with recursive eval as (
select obj->>'car' as car
, obj->'cdr' as cdr
, 1 as depth
from lisp
union all
select cdr->>'car' as car
, cdr->'cdr' as cdr
, depth + 1 as depth
from eval
where (cdr->'cdr') is not null
)
select string_agg(car, '' order by depth) as msg
from eval
;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment