How do you iterate over json when the schema is not known up front?

119 Views Asked by At

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

1

There are 1 best solutions below

0
On BEST ANSWER

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 and JsArray (there are more subtypes, check the docs for the rest)

Your question seems to be geared towards JSON Objects and JsObject has an underlying: Map[String, JsValue] which is a Map and you should easily be able to iterate over the keys/entries.

Some pseudo Scala code (did not compile):

val allowedValues = Set("name", "age", "job")
val parsedJson: JsValue = ....

parsedJson match {
  case jsonObject: JsObject =>
    val underlyingObjectValues = jsonObject.underlying
    val keysNotInAllowedSet = underlyingObjectValues.keys.diff(allowedValues)
    // Add keysNotInAllowedSet to the error list
  case _ => // Possible parse JsArray, etc.
}