Squash "value" key in JSON

I’d like to change the format of the JSON generated from Repeater types to not include the “value” key and just skip it. For example, my data has a few Repeaters of Sets that end up with JSON that looks like:

...
...
"hints": [
{
    "value": {
        "image": "main\/image1.png",
        "prompt": "This is hint 1."
    }
},
{
    "value": {
        "image": "main\/image2.png",
        "prompt": "This is hint 2."
    }
}
],
...

and what I want is this:

...
"hints": [
{
    "image": "main\/image1.png",
    "prompt": "This is hint 1."
},
{
    "image": "main\/image2.png",
    "prompt": "This is hint 2."
}
],
...

I read another post by @pauloamgomes that hints to using a hook which I’m trying to reference, but I need help getting it to work. This is what I have so far:

$app->on('collections.find.after', function($name, &$entries) use($app) {
  
  function simple_value(&$entry) {
    foreach ($entry as $name => &$value) {
      if (strcmp($name, 'value') == 0) {
        $entry[$name] = $value;
      }
      if (is_array($value) || is_object($value)) {
        foreach ($value as $key => &$child) {
          simple_value($child);
        }
      }
    }
  }

  simple_value($entries);
});

This doesn’t seem to do anything. Am I on the right track? Is there an easy way to debug this and see what’s going on? I’m a bit new to PHP and not familiar with the toolset.

Thanks!

1 Like

You could use a modified repeater field to store the data in your prefered way. I answered this a few days ago and updated my simple-repeater field to be compatible with set fields.

See: Fieldtype to get array of objects - #2 by raffaelj

This one should work. Replace collectionname with the name of your collection, that contains the repeater fields.

// don't convert found data while editing in backend
if (COCKPIT_API_REQUEST) {

    // Don't fire on all collections, but only on the one named "collectionname"
    $app->on('collections.find.after.collectionname', function($name, &$entries) {

        // iterate over entries and replace the values
        foreach ($entries as &$entry) {

            $entry = isset($entry['value']) ? $entry['value'] : null;

        }

    });

}