Proper JSON encoding with PHP

I’ve decided to write posts that may wind up just being a reference to msyelf. There have been so many times that I wish I could remember how I did things a certain way, and I think that my blog could be a good archive of past programmering. I mean, I’d certainly love it if you did find them useful, but don’t be mad if you don’t.

I recently ran into this nasty bug with our api at work. We started receiving an empty response body along with no errors. Very long story short, it wound up being a json encoding issue. We were using Zend_Json to encode, and my thinking was that there would be some nice wrappers around json_encode to help out with Exceptions, etc. It turns out it just winds up calling json_encode unless you explicitly tell it to use Zend’s built-in encoder.

The problem with json_encode is that it doesn’t throw any sort of exception if it can’t encode what you throw at it. Heck, it doesn’t even return false. What you get back is a nice NULL. That NULL wound up being blindly given back in our api. Oddly enough, errors do happen, and you can get them. Check out json_last_error_msg(). Knowing this, you can handle errors, log them, and maybe even send a friendly message back in the api. In our case, we threw an exception with the attempted string to encode, and the error message that came back from json_last_error_msg.

Check out Handling JSON like a boss in PHP for more info.

4 Comments

  1. This is interesting and I never knew about json_last_error_msg(). It is interesting because json_encode() claims to show false on error. I wonder what would happen if you set the option JSON_PARTIAL_OUTPUT_ON_ERROR if anything would come back.

    Reply
    • One other thing I noticed in the comments of json_encode, but have yet to verify is that:

      Although this is not documented on the version log here, non-UTF8 handling behaviour has changed in 5.5, in a way that can make debugging difficult.

      Passing a non UTF-8 string to json_encode() will make the function return false in PHP 5.5, while it will only nullify this string (and only this one) in previous versions.

      Reply
  2. I always wondered why those api’s would occasionally return null instead of the data, and I never had enough time to figure it out. I’m glad you found it, and hopefully I’ll remember this for future JSON adventures.

    One other function that needs this treatment is parse_ini_file(). When it can’t parse the file it issues warnings. I found it beneficial to call error_get_last() when it returns false, at least then you can throw more meaningful exceptions.

    Reply

Post a Comment

I promise not to publish your email address.

*
*