Search code examples
magnolia

Why does jsonfn.expand include null values?


I'm building up an array of JSON objects using jsonfn and rendering them on the JavaScript window object.

[#assign json = []]
[#list articles as article]
  [#assign json += [jsonfn.from(article).add("categories", "title", "@name").expand("categories").inline().print()]]
[/#list]

<script>
  window.articles = [${json?join(",")}];
</script>

While effective, the expanded categories field (expand("categories")) sometimes includes null values.

{
  "categories": [
    {
      "displayName": "Example Category",
      "@name": "example-category"
    },
    null
  ],
  "title": "Example Article",
  "@name": "example-article"
}

This requires me to add an instanceof Object check when filtering in JavaScript so that I don't get a null error.

export const filterArticles = (selectedCategory, articles) => {
  return articles.filter((article) => {
    return article.categories.find((category) =>
      category instanceof Object && category['@name'] === selectedCategory
    );
  });
};

Why does jsonfn.expand sometimes output null values? Why isn't there a null safety check to avoid including them in the rendered output?


Solution

  • See JSONFN-5 ticket. Should be working without printing nulls as of version 1.0.9(-SNAPSHOT). Alternatively, pull the latest code from github and build it yourself.