views:

36

answers:

5

I have json object like this, the site is running codeigniter which is ultimately the problem.

var obj = {

      states : {
         'state' : {cities : ['city', 'city2', 'another']},
      }
   }

the problem is some states have special characters like , or spaces. When those states get added I get a Disallowed Key Characters. error. If I remove the special chars and the space it works fine.

Do I have to resort to some other method?

A: 

I'm not sure if this is it, but those characters aren't allowed in a url. Maybe you're using GET? Try using POST.

Matthew
I am using post.
Mike
A: 

Try using this function at PHP side.

function fixjson($json){
return '('.preg_replace('/^([^[{].*)$/', '[$1]', $json).')';}

$json = fixjson($json);
Moe Sweet
the json never makes it to the php side.
Mike
A: 

Some characters are just disallowed. You can urlencode() them before inserting them into the JSON - see http://stackoverflow.com/questions/2627918/codeigniter-disallowed-key-characters-via-get

TML
the problem is, javascript creates the object so urlenecode is off limits.
Mike
Try encodeURIComponent(str) - see https://developer.mozilla.org/En/Core_javascript_1.5_reference:global_functions:encodeuricomponent
TML
A: 

It turns out that this error was caused by CI's input library. On line 215 you will find _clean_input_keys function which uses preg_match() to disallow certain characters in your keys. So when you send JSON around and php recieves it as an array it can throw an error.

To fix this you can either extend the library or edit the CI core.

Mike
A: 
  1. You should encode your json at all times.
  2. If you still need those chars in a URL, you can configure those in CI, there is no need to extend anything or touch the core (in your system/application/config/config.php file):

    $config['permitted_uri_chars'] = 'a-z 0-9~%.:_-|=-@';

Ferdy