Deserializing Data
When adding images to our recipes grid, we had to do quite a bit of traversing to get the data we needed due to the structure of relationships and included data in JSON:API responses.
We can simplify this by using the serializer
option when creating our client instance, along with a library like Jsona. This will provide a simplified and flattened response when data is returned from the server.
The serializer Option
Revisiting the creation of our JsonApiClient instance, we can add an options object as the second argument. This object can include a serializer property, which can be used to transform the data provided by JSON:API
.The provided serializer object can have two methods: deserializer
and serializer
. An instance of Jsona fits that signature.
Let’s update our client instance to use the Jsona
serializer.
Deserializing Data
Now that we have provided a compatible serializer, all data sourced from Drupal will be deserialized automatically.
Taking a look at the recipes
object, you’ll see that the data is now flatter and easier to access. For example, field_media_image is now a direct property of the recipe data, and the thumbnail file is directly accessible from this media entity. We could get the thumbnail url for the first recipe result like this:
Refactoring the Recipe Grid
Let’s see the impact that working with deserialized data has on our recipe grid. We can refactor the grid to use this new flattened data structure.
Umami Recipes
Deep mediterranean quiche
Difficulty: medium
View RecipeVegan chocolate and nut brownies
Difficulty: medium
View RecipeSuper easy vegetarian pasta bake
Difficulty: easy
View RecipeWatercress soup
Difficulty: easy
View RecipeVictoria sponge cake
Difficulty: easy
View RecipeGluten free pizza
Difficulty: medium
View RecipeThai green curry
Difficulty: medium
View RecipeCrema catalana
Difficulty: medium
View RecipeFiery chili sauce
Difficulty: easy
View RecipeBorscht with pork ribs
Difficulty: medium
View RecipeThe end result is the same, so choose the option that is best for your team. Use the client default to work with the JSON:API
response as is, or use the serializer
option to work with a simplified object.
Serializing Data
In cases where you need serialize or re-serialize the data before sending it to the server, you will have access to the serializer
method on the client instance. Below is an example of using Jsona’s serializer.
Since the signature of these serializer methods tend to vary, the JSON:API client doesn’t currently serialize data automatically, but it will be available for use if provided.