I've been reading Play's docs here about json parsing, but it all seems tailored to parsing Json that you know the structure ahead of time (e.g. it maps nicely to an existing model). This, to me, is further reflected in the fact that, more or less, the api for the json
module is /
and //
, which look up structures by name.
While ultimately I am trying to convert to a model, this is a public API point, so I want to be friendly along the way and collect any errors. Namely, incorrect fields.
In pseudo code, id like to be able to do something like:
allowed_values = ['name', 'age', 'job']
field_errors = []
for key, value in json:
if key not in allowed_values:
field_erros.append(key)
That'd allow me to return something like unrecognized field "naem"
, which I think I handy.
Can this (easily) be done in scala
Yes, it's possible, although you will have to write a bit of custom code, so I wouldn't really consider it "easy".
Play parses JSON to a
JsValue
trait. You can pattern match on that trait and it has 2 subtypes that are of interest to you:JsObject
andJsArray
(there are more subtypes, check the docs for the rest)Your question seems to be geared towards JSON Objects and
JsObject
has anunderlying: Map[String, JsValue]
which is aMap
and you should easily be able to iterate over the keys/entries.Some pseudo Scala code (did not compile):