Displaying error message using json encode


I wanted to display the error messages in druapl 8 using json-encode.

I tried the following method, “Link” But i get The Website encountered an error message when I implement that code. If i comment out my hook_form_alter function then there is no error.

But still the errors are not shown. I have no idea how to implement this. Yes, there is a way to handle the errors using status messages but i don’t want the result in that way. 

Can someone guide me how to catch the errors and display them below the respective fields using json-encode?


Drupal version: 

Source: https://www.drupal.org/taxonomy/term/4/feed