JSON Encode and Decode Problems

  1. JSON.stringify(obj);
  2. If value includes double quote or single quote, and need to be passed from php to javascript:
    $banners = preg_replace("/\\\'/", ''', $banners);
    $banners = preg_replace('/\\\"/', '"', $banners);
  3. Put JSON string in HTML tag attributes: Double quote must be converted to "
    e.g. $version = str_replace('"', '"', $version);

Summary steps:

  1. JS send to PHP: var json = '{"id":1,"title":JSON.stringify(title)}';
  2. Save to DB in PHP: Don't need to use json_encode()
  3. Retrieve by JS: $.parseJSON(json);
  4. Retrieve by PHP: json_decode($json);