first,  is sometimes an integer so don't json encode it then. Second, if it's not an integer, it might be a string with unwanted leading spaces so trim it, and json_encode it. Third, it's going in an html attribute so escape the quotes and any other special characters.