Skip to content

Instantly share code, notes, and snippets.

@baikho
Created September 27, 2025 22:02
Show Gist options
  • Select an option

  • Save baikho/f511c7087014aaba57e1d7d5855def56 to your computer and use it in GitHub Desktop.

Select an option

Save baikho/f511c7087014aaba57e1d7d5855def56 to your computer and use it in GitHub Desktop.
Drupal Migrate Plus JSON Single Item Parser
<?php
namespace Drupal\my_module\Plugin\migrate_plus\data_parser;
use Drupal\migrate\MigrateException;
use Drupal\migrate_plus\Plugin\migrate_plus\data_parser\Json;
/**
* JSON data parser for APIs returning a single object per URL.
*
* Wraps single objects in an array so the migration system can handle them
* as individual items.
*
* @DataParser(
* id = "json_single_item",
* title = @Translation("JSON Single Item")
* )
*/
class JsonSingleItem extends Json {
/**
* {@inheritdoc}
*/
protected function openSourceUrl(string $url): bool {
// In case of a sequence of single JSON URLs, we don't want to halt migration.
try {
return parent::openSourceUrl($url);
}
catch (MigrateException $e) {
// Log the error and skip this URL instead of failing the entire migration.
\Drupal::logger('my_module')->error('Skipping failed URL @url: @error', [
'@url' => $url,
'@error' => $e->getMessage(),
]);
return FALSE;
}
}
/**
* {@inheritdoc}
*/
protected function getSourceData(string $url, string|int $item_selector = ''): array {
$source_data = parent::getSourceData($url, $item_selector);
// If the response is a single object (not an array), wrap it in an array
// so the migration system can process it as one item.
return [$source_data];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment