Parsing nodes on JSON with Scala - -
i've been asked parse json file buses on specified speed inputed user.
the json file can downloaded here
it's this:
{ "columns": [ "datahora", "ordem", "linha", "latitude", "longitude", "velocidade" ], "data": [ [ "04-16-2015 00:00:55", "b63099", "", -22.7931, -43.2943, 0 ], [ "04-16-2015 00:01:02", "c44503", 781, -22.853649, -43.37616, 25 ], [ "04-16-2015 00:11:40", "b63067", "", -22.7925, -43.2945, 0 ], ] }
the thing is: i'm new scala , have never worked json before (shame on me). need "ordem", "linha" , "velocidade" data node.
i created case class enclousure data later on specified speed.
case class bus(ordem: string, linha: int, velocidade: int)
i did reading file textfile , spliting. although way, need foreknow content of file in order go lines after data node.
i want know how using json parser. i've tried many solutions, couldn't adapt problem, because need extract lines data node instead of nodes inside 1 node.
can me?
ps: sorry english, not native speaker.
first of all, need understand different json data types. basic types in json numbers, strings, booleans, arrays, , objects. data returned in example object 2 keys: columns
, data
. columns
key has value array of strings , numbers. data
key has value array of arrays of strings.
you can use library playjson work type of data:
val js = json.parse(x).as[jsobject] val keys = (js \ "columns").as[list[string]] val values = (js \ "data").as[list[list[jsvalue]]] val busses = values.map(valuelist => { val keyvalues = (keys zip valuelist).tomap { ordem <- keyvalues("ordem").asopt[string] linha <- keyvalues("linha").asopt[int] velocidade <- keyvalues("velocidade").asopt[int] } yield bus(ordem, linha, velocidade) })
note use of asopt
when converting properties expected types. operator converts key-values provided type if possible (wrapped in some
), , returns none
otherwise. so, if want provide default value instead of ignoring other results, use keyvalues("linha").asopt[int].getorelse(0)
, example.
you can read more play json methods used here, \
, as
, , asopt
in their docs.
Comments
Post a Comment