jsop: Cherry picking in JSON objects

[ bsd3, codec, decoder, library ] [ Propose Tags ]

Simple single record picking out of nested JSON objects


[Skip to Readme]

Downloads

Maintainer's Corner

Package maintainers

For package maintainers and hackage trustees

Candidates

  • No Candidates
Versions [RSS] 0.1.0.0, 0.2.0.0, 0.2.0.1
Change log ChangeLog.md
Dependencies aeson, base (>=4.7 && <5), containers, generics-sop, lens, lens-aeson, monoidal-containers, protolude, string-interpolate, tasty, tasty-discover, tasty-hspec, text [details]
License BSD-3-Clause
Copyright Global Access GmbH, Paolo Veronelli 2020
Author Paolo Veronelli
Maintainer paolo.veronelli@gmail.com
Category Decoder
Uploaded by PaoloVeronelli at 2020-08-07T15:21:14Z
Distributions
Downloads 517 total (13 in the last 30 days)
Rating (no votes yet) [estimated by Bayesian average]
Your Rating
  • λ
  • λ
  • λ
Status Docs available [build log]
Last success reported on 2020-08-07 [all 1 reports]

Readme for jsop-0.1.0.0

[back to package description]

jsop, JSON record cherry picker

JSOP is good for picking out a product type value from nested json objects

Example

Preamble


{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}

import Data.Aeson
import Data.Aeson.Lens
import Data.String.Interpolate
import qualified Data.Text as T
import Generics.SOP
import Generics.SOP.TH
import JSOP.Parse
import Protolude hiding (All, optional, (:*:))
import Data.Maybe (fromJust)

Given we have a SOP encoding of the record (tuples are good).

The jSOP memoize the keys path structure so jSOP f g should be curried to repeat on multiple values. The Value will be scanned only one time, despite the paths are always expressed from the root. Order is restored by a final lookup.

data ABC = ABC Text Int Int deriving (Show, Eq)

deriveGeneric ''ABC

Then we need a product of pickers with the same shape as our product type.

In this case I choose to encode paths joining json keys with /

cherryPickABC :: NP (Parser Text) '[Text, Int, Int]
cherryPickABC =
  required "object 1 / a string" _String
    :* required "object 2 / a number" _Integral
    :* optional "object 4 / a number" 42 _Integral
    :* Nil

Given the next json structure

jsonWithABC :: Value
jsonWithABC = fromJust . decode $ [i| 
  {
    "object 1": 
      { "a string": "ciao"
      , "ignore me" : 34
      }
  , "object 2": 
      { "a number": 2
      , "object 3": {}
      }
  , "object 4": {
      "a plumber" :43
      } 
  }
  |]

We can cherry pick the scattered ABC with

abc :: ABC
Right abc = jSOP (T.splitOn " / ") cherryPickABC jsonWithAB