bug #3962 Proper escaping of JSON export

We now use json_encode instead of home made encoder. Also we now
generate JSON data on the fly, what reduces memory usage.