In PHP, I put the $data_attributes array into the data-additional-color-data attribute of one HTML element:
$data_attributes = [
312 => [
'name' => 'Black',
'hex' => '#000000',
'src' => 'http://sitename/files/pms_colors/Black.png'
],
313 => [
'name' => 'Metallic',
'hex' => '#D3D4DE',
'src' => 'http://sitename/files/pms_colors/Metallic.png'
]
];
$entity_form['field_pms_colors']['#attributes']['data-additional-color-data'] = Json::encode($data_attributes);
And I see in the browser’s devtools that in the markup the element looks like this:
<div class="field--name-field-pms-colors" data-additional-color-data="{"312":{"name":"Black","hex":"#000000","src":"http:\/\/sitename\/sites\/default\/files\/pms_colors\/Black.png"},"313":{"name":"Metallic Silver","hex":"#D3D4DE","src":"http:\/\/sitename\/sites\/default\/files\/pms_colors\/Metallic%20Silver.png"}}"></div>
This is one element and its properties must be with it:
312 => [
'name' => 'Black',
'hex' => '#000000',
'src' => 'http://sitename/files/pms_colors/Black.png'
],
>Solution :
There is no specific decoding to be done, as JavaScript will decode this when accessing the data attribute like this:
// Get the HTML element of interest:
let element = document.querySelector("div.field--name-field-pms-colors");
// Read the data- attribute of interest:
let content = element.dataset.additionalColorData;
// Output it: no decoding of HTML entities needed -- there is no literal "
console.log(content);
// Parse the JSON into an object
let obj = JSON.parse(content);
// Use the object...