Convert page content to JSON

Hey everyone! :wave:

I am trying to output a complete JSON edition of a page. Here I encounter the problem that fields like images, tags or structures are not automatically converted. These must be unpacked separately.

Is there a central method to convert the complete content into a JSON?

At the moment I only see the possibility to go through each field individually, find out what type of field it is and convert it individually. This requires all field types in the code to be hardwired.

I would be very happy about a tip, which leads me in a better direction.

You don’t have to hardwire the field, but can fetch them from the blueprint, see $page->blueprint() in the docs and this cookbook recipe: https://getkirby.com/docs/cookbook/templating/blueprints-in-frontend

So I would look up the type of each field in the blueprint and make a distinction in the code, e.g. for tags I would call the separate function.

But there is no generic way to unpack the fields, is there? Or is there a definition somewhere, which function should be called for which field type?

No, because there is no 1:1 correlation, e.g. a files field can be used with toFile() for a single file, or toFiles() for multiple files etc. so it really depends on the desired output.

Maybe it would make more sense to create a JSON content representation for each page.

As @pixelijn mentioned, here’s a cookbook recipe for the content representation.