Fix JSON encoding, where training '}' may not be written correctly for certain input buffer lengths