Converting Tags string to an array for json REST API


#1

Hi there, I am using Lord Executor’s kirby json api plugin:

https://github.com/lord-executor/kirby-json-api

and in the response, tags are output as a comma-separated string. I would like the response to display each tag as an item in an array. e.g. currently they show as:

tags: "commercial,editorial,test",

but I would like

tags: ["commercial", "editorial", "test"],

Is it possible to do this?

I found the ~/panel/app/fields/tags/tags.php file here – but not sure this contains what I need?


#2

Please read the documentation of the plugin carefully: https://github.com/lord-executor/kirby-json-api#selecting-and-mapping-fields

Don’t mess with the source code. As it says in the plugin documentation, the default is that the field value is rendered as is in the Json result. This can be changed using the mapfield() method.


#3

Thanks very much for the pointers Sonja –

I can see that I could possibly use $field->split($separator = ',') but I’m unsure how I might apply mapField() to the ‘Tags’ field specifically – previously I’ve added more metadata to the files section:

		foreach ($page->files() as $file) {
			$collection = new JsonFieldCollection();
			$collection->addFields([
				'url' => new StaticField($file->url()),
				'name' => new StaticField($file->name()),
				'extension' => new StaticField($file->extension()),
				'size' => new StaticField($file->size()),
				'niceSize' => new StaticField($file->niceSize()),
				'mime' => new StaticField($file->mime()),
				'type' => new StaticField($file->type()),
			]);

			$files[] = $collection;
		}

But this was already declared explicitly in the file JsonApiUtil.php whereas Tags is not.


#4

As in the example, I think:

->mapField('tags', function ($field) {
		return $field->split();
	}