I'm certainly no expert but this code seems to meet your needs. I've only really focused on the "txtContent" field so you can largely ignore the rest.
In plain English, it is counting the length of the string. If it's 10 characters long, it displays it as (xxx) yyy-zzzz, if it is 7 characters, it displays it as xxx-yyyy. If it is neither, it displays "Invalid" but you could easily adapt it to meet any other requirements you may have. This was applied to a column with a type of Number.
Finding the length of the string was an unknown for me but I found this on the SharePoint Online column formatting guide
indexOf Since the operator length doesn't work for string value types ( it will return 1 or 0 ), indexOf can serve us as a nice workaround to get the length of a string, for instance: indexOf([$column1] + '^', '^'). We will use '^' or any other character we may want to use to find out the end of the string.
My JSON code:
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
"elmType": "div",
"style": {
"box-sizing": "border-box",
"padding": "0 2px"
},
"attributes": {
"class": ""
},
"children": [
{
"elmType": "span",
"style": {
"line-height": "16px",
"height": "14px"
},
"attributes": {
"iconName": "",
"class": ""
}
},
{
"elmType": "span",
"style": {
"overflow": "hidden",
"text-overflow": "ellipsis",
"padding": "0 3px"
},
"txtContent": "=if(indexOf(@currentField + '^', '^') == 10,'('+substring(toString(@currentField),0,3)+') '+substring(toString(@currentField),3,6)+'-'+substring(toString(@currentField),6,10),if(indexOf(@currentField + '^', '^') == 7,substring(toString(@currentField),0,3)+'-'+substring(toString(@currentField),3,8),'Invalid')",
"attributes": {
"class": ""
}
}
]
}