Reading JSON Data in the Backend

Hello,

I would like to read the data from a json file (content/formdata.json) and output it in the backend. What is the best way to do this?

Best regards
Maras

A) dump the pretty printed json in a info section via the query language. Untested code but should get you started.

jsonout:
   type: info
   text: "{{ page.myjsonfield.toJsonPretty }}

custom plugin with fieldMethods

<?php
Kirby::plugin('me/prettyjson', [
    'fieldMethods' => [
         'toJsonPretty' => function($field) {
             if ($field->isNotEmpty()) {
                   $field->value = json_encode(json_decode($field->value, true), JSON_PRETTY_PRINT);
             }
             return $field;
         },
    ],
]);

B) use a plugin (sadly abandoned) GitHub - OblikStudio/kirby-json: JSON component and field for Kirby.

C) you could create a custom section: Custom Panel section | Kirby CMS

(edited: fixed typo fieldsMethods to fieldMethods)

Hi bnomei,

thank you for your reply. At least I can now create my own field. Now the question is how to reference the json file:

text: ā€œ{{ page.myjsonfield.toJsonPretty }}

I think I still have to include my json files here. What is the correct spelling here if the data can be found under content/registrations.json?

Sorry, Iā€™m not that familiar with this :see_no_evil:

in any blueprint

      myprettyjson:
        type: info
        text: "{< site.contentformdata >}"

site/plugins/jpp/index.php

<?php

use Kirby\Filesystem\F;

Kirby::plugin('myplugin/contentformdata', [
    'siteMethods' => [
        /*
         * Pretty print the content of the formdata.json file
         *
         * use in blueprint query language like this:
         * myprettyjson:
         *   type: info
         *   text: "{< site.contentformdata >}"
         */
        'contentformdata' => function(): string {
            $filePath = kirby()->roots()->content() . '/formdata.json';
            if (!F::exists($filePath)) {
                return 'File not found';
            }

            $content = F::read($filePath);
            $data = json_decode($content, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return 'Error decoding JSON';
            }
            $pretty = json_encode($data, JSON_PRETTY_PRINT);

            return str_replace(' ', '&nbsp;', $pretty);
        },
    ],
]);

content/formdata.json

{
  "hello": "world"
}

output

CleanShot 2024-09-18 at 19.11.04

Very cool!!! THANK YOU for your quick help!!!

1 Like