haskell - Finding a value in ByteString (which is actually JSON) -


a web service returns response bytestring

  req <- parseurl "https://api.example.com"   res <- withmanager $ httplbs $ configreq req   case (hashmap.lookup "result" $ responsebody res) of .... -- error - responsebody returns bytestring          configreq r = --...... 

to more specific, responsebody returns data in bytestring, although it's valid json. need find value in it. obviously, easier find if json , not bytestring.

if that's case, how convert json?

update:

decode $ responsebody resp :: io (either string aeson.value) 

error:

couldn't match expected type `io (either string value)'                 actual type `maybe a0' 

you'll find several resources converting bytestring json. simplest use cases on hackage page itself, , rest can infer using type signatures of entities involved.

https://hackage.haskell.org/package/aeson-0.7.0.6/docs/data-aeson.html

but here's super quick intro json aeson: in languages, have things this:

somestring = '{ "name" : ["value1", 2] }' adict = json.loads(somestring) 

this great, because json has 1 one mapping fundamental data-structure of language. containers in dynamic languages can contain values of type, , moving json data structure single step.

however, not case haskell. can't put things of arbitrary types container type (a list, or dictionary).

so aeson neat thing. defines intermediate haskell type you, maps directly json.

a fundamental unit in aeson value. value can contain many things. integer, string, array, or object.

https://hackage.haskell.org/package/aeson-0.7.0.6/docs/data-aeson.html#t:value

an aeson array vector (like list better) of values , aeson object hashmap of text values

the next interesting step can define functions convert aeson value haskell type. completes loop. bytestring value custom type.

so implement parsejson , tojson functions convert aeson values type , vice-versa. bit converts bytestring valid aeson value implemented aeson. heavy lifting done.

just important note, aeson bytestring lazy bytestring, might need strict lazy helpers.

stringtolazy :: string -> bytestring stringtolazy x = data.bytestring.lazy.fromchunks [(data.bytestring.char8.pack x)]  lazytostring :: bytestring -> string lazytostring x = data.bytestring.char8.unpack $ data.bytestring.char8.concat $ data.bytestring.lazy.tochunks 

that should enough started aeson.

--

common decoding functions aeson:

decode :: bytestring -> maybe yourtype eitherdecode :: bytestring -> either string yourtype. 

in case, you're looking eitherdecode.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -