1

I am having a problem where json can encode an array But then it can't properly decode it due to special characters.

I found this function on stackoverflow that tries to help:

function escapeJsonString($value) 
{  # list from www.json.org: (\b backspace, \f formfeed)
                $escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
                $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
                $result = str_replace($escapers, $replacements, $value);
                return $result;
    }

But it is only a list of characters, every time I get a new special character I have to manually deal with it and add it to the character and its replacement list.

How do I properly take care of this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user2123244
  • 99
  • 1
  • 4
  • 3
    if the string is utf-8 json_encode does correctly handle special characters, so does json_decode, usually there is no extra replacement required if u are working with valid json, post your json code please! – x4rf41 Mar 01 '13 at 11:14
  • Have you tried with urlencode() http://php.net/manual/en/function.urlencode.php? – ka_lin Mar 01 '13 at 11:14

2 Answers2

0

try cleaning your json

$cleanJsonData = preg_replace("/[[:cntrl:]]/", "", $jsonData);
$myData = json_decode($cleanJsonData, TRUE);
Dino Babu
  • 5,814
  • 3
  • 24
  • 33
0

json_decode excepts the input string to be utf-8 encoded.

<?php
$json = json_decode(utf8_encode($str));

This should work.

Licson
  • 2,231
  • 18
  • 26