Wordpress - Why WordPress choose data serialization over json_encode?

I think, not 100% sure that this was the real reason the WP developers took this approach, but common sense tells me that serialize preserves the variable types and have a mini built in error detection, and json stores only string values { key : value }, so when you go back to PHP you will have to guess the format, or make a parser for it. This will force you to have two different ways to handle your data: previous, to storing the data as json and after decoding the json it will come back as a totally different object.

This is the main reason the difference in size, PHP is storing not only an array; it is storing how many elements were in the array when it was serialized, their types, and their values.

You are not storing only key value pairs on the database but you may also be storing an object with different variable types.


JSON encoding was introduced in PHP 5.2, WordPress is way older, and it was born (and designed for) PHP 4.

Data serialization is a pervasive thing in WordPress, so moving from PHP serialization to JSON encoding would mean a huge backward compatibility problem, and if I know WordPress a little, that will never happen.

That said, if you think that JSON encoding is better for you than PHP serialization, just use it.

If you pass a string (that is the JSON-encoded version of your data) to post meta functions WordPress will not touch it, but then you need to remember to JSON-decode data on retrieval.

If DB storage size is very important for you, that it probably worth the additional work, otherwise just let WordPress use what it uses and don't care about it.

Maybe, you can evaluate if it is the case of custom tables to save your data.


I am tempted to close this as "subject to opinion" but I think there are a couple of good answers to the question. I am going to go with "history".

1) json_encode is relatively new in PHP core.

json_encode

(PHP 5 >= 5.2.0, PECL json >= 1.2.0) json_encode — Returns the JSON representation of a value

http://php.net/manual/en/function.json-encode.php

json_encode would not have been reliable in WordPress' early days. It was only rolled into "core" PHP in 5.2, though it was available as a PECL extension long before that.

Second, if you feed an object such as a WP_Query object into json_encode you get a stdClass object on json_decode. serialize/unserialize will preserve the object.