JSON Encoding in WordPress 4.1

Earlier in the year, we noticed a problem with JSON in WordPress. The JSON spec very explicitly notes that it only supports UTF-8, whereas WordPress can use any character set that MySQL supports. So, for sites that didn’t use MySQL’s utf8 or utf8mb4 character sets, this generally presented itself as json_encode() returning false; which resulted in either invalid JSON being returned from an Ajax request, or a JavaScript error in some embedded code.

To fix this, WordPress 4.1 now includes a shiny new function that we recommend for all plugins and themes:

wp_json_encode()

Usage for wp_json_encode() is identical to json_encode(). It works by trying a json_encode(), then checking if that encoded properly. If it failed, wp_json_encode() will go through whatever lump of data you passed to it, convert it to UTF-8, then return it as JSON.

Have fun with WordPress 4.1, and see you next year for new and exciting functionality coming to a WordPress install near you!