WelcomeTo
WelcomeTo

Reputation: 20581

Prevent JSON4S from skipping JSON objects with a missing field

Let's suppose I have a simple JSON array like this:

[ 
  { 
    "name": "Alex",
    "age": 12
  },
  { 
    "name": "Peter"
  }
]

Notice that the second object doesn't have an age field.

I'm using JSON4S to query JSON (using the for-comprehension style to extract values):

 for {
      JArray(persons) <- json
      JObject(person) <- persons
      JField("name", JString(name)) <- person
      JField("age", JString(age)) <- person
 } yield new Person(name, age) 

The problem for me is that this expression will skip the second object (the one with the missing age field). I don't want to skip such objects; I need to get it as null or better as None.


This answer gives an example of how to deal with null values in JSON using custom extractors, but it works only if the field is present and if its value is null.

Upvotes: 2

Views: 559

Answers (1)

Aivean
Aivean

Reputation: 10882

Deconstructing objects in json4s may lead to some inconvenience, as you no longer can use fancy \ and \\ queries.

I prefer to do something like that:

for {
    JArray(persons) <- json
    person@JObject(_) <- persons
    JString(name) <- person \ "name"
    age = (person \ "age").extractOpt[Int]
     } yield (name, age)

res7: List[(String, Option[Int])] = List(("Alex", Some(12)), ("Peter", None))

This example also illustrates two alternatives how object fields can be extracted (you can also use name = (person \ "name").extract[String] instead).

Upvotes: 2

Related Questions