module Text.JSONb.Path(
Selector
, key
, idx
, Path(..)
, get
, getOne) where
import Data.Maybe
import qualified Data.Trie as T
import qualified Text.JSONb as J
import qualified Data.ByteString as B
import qualified Data.ByteString.UTF8 as U8
data Selector
= Key B.ByteString
| Idx Int
key :: String -> Selector
key = Key . U8.fromString
idx :: Int -> Selector
idx = Idx
infixr 7 :=>
data Path
= Fail
| Yield
| Selector :=> Path
| All Path
| Compute (J.JSON -> Path)
get :: Path -> J.JSON -> [J.JSON]
get Fail _ = []
get Yield x = [x]
get (Key k :=> p) (J.Object t) | Just x <- T.lookup k t = get p x
get (Key _ :=> _) _ = []
get (Idx i :=> p) (J.Array xs) | (_, (y:_)) <- splitAt i xs = get p y
get (Idx _ :=> _) _ = []
get (All p) (J.Array xs) = concatMap (get p) xs
get (All _) _ = []
get (Compute f) j = get (f j) j
getOne :: Path -> J.JSON -> Maybe J.JSON
getOne p = listToMaybe . get p