Minecraft – How to test for a named barrel/chest? (1.14.4)

minecraft-commandsminecraft-java-edition

I've been trying to make a command block contraption that replaces a named barrel in Minecraft 1.14.4

I originally substituted the block information from a setblock command into a fill command but it wouldn't work. even though the setblock command works perfectly

/setblock ~1 ~ ~ minecraft:barrel{CustomName:"\"a\""}
/fill ~-8 ~-8 ~-8 ~8 ~8 ~8 minecraft:wet_sponge replace minecraft:barrel{CustomName:"\"a\""}

I then tried testing for the block using this

/execute if block ~ ~-1 ~ minecraft:barrel{CustomName:"\"a\""}

still wouldn't work.
I did try searching a lot and this is my last option
I don't know this is a bug or what but perhaps I'm still doing something wrong.

Best Answer

Typically, the best way to determine what data you are checking for is to just check the block data directly with the command /data get block ~ ~-1 ~. That way, you will know exactly what you are checking for. In this case, you get the data:

{CustomName:'{"text":"a"}'...}

This reveals exactly why your search isn't detecting the barrel. While the single quotes don't matter so long as you escape the quotes on the inside, you need to actually check for the .json data and not the word "a" directly. This means that you would run this kind of command:

fill ~-8 ~-8 ~-8 ~8 ~8 ~8 minecraft:wet_sponge replace minecraft:barrel{CustomName:"{\"text\":\"a\"}"}

which detects the barrel correctly.