Skip to content

Instantly share code, notes, and snippets.

@Muqsit
Last active November 11, 2023 11:53
Show Gist options
  • Save Muqsit/1f9a2f221761750846e2f8c215dfadda to your computer and use it in GitHub Desktop.
Save Muqsit/1f9a2f221761750846e2f8c215dfadda to your computer and use it in GitHub Desktop.
NBT CompoundTag to JSON in PocketMine-MP using a stack for iterative node traversal
<?php
declare(strict_types=1);
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\player\Player;
use pocketmine\Server;
$server = Server::getInstance();
assert(isset($sender) && $sender instanceof Player);
if(!($sender instanceof Player)){
return;
}
$nbtToJson = static function(CompoundTag $nbt) : array{
$data = $nbt->getValue();
$stack = [];
foreach($data as &$v){
$stack[] = &$v;
}
unset($v);
while(($index = array_key_last($stack)) !== null){
$v = &$stack[$index];
unset($stack[$index]);
$v = $v->getValue();
if(is_array($v)){
foreach($v as &$vv){
$stack[] = &$vv;
}
unset($vv);
}
}
return $data;
};
$item = $sender->getInventory()->getItemInHand();
$nbt = $item->getNamedTag();
$data = $nbtToJson($nbt);
echo json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment