带有特殊字符的Json_decode

我通过jQuery Ajax将数据作为JSON发布到我的服务器上遇到了一个大问题。 JSLint说数据没问题,请求的Content-Type设置为application/x-www-form-urlencoded; charset=UTF-8 application/x-www-form-urlencoded; charset=UTF-8 。 服务器在PHP 5.2.11上运行,所以我不能使用json_last_error()

我尝试了url_decode,utf8_decode和html_entities_decode,但似乎没有任何效果。

var_dump(json_decode($jdata)); 返回null,但如果我执行var_dump($jdata)一切看起来都可以。 $jdata是post数据: $jdata = $this->input->post('requestdata');

这里从Firebug获取一些示例后期数据:

 { "projectnumber": "345", "projecdescription": "345", "articles": [ { "position": 1, "article_id": 677, "online_text": "3 Behälter; Band I-III nach indiv. Stückliste, Sprache: DE - Sprache: de" }, { "position": 2, "article_id": 678, "online_text": "2 Behälter; Band I-III nach indiv. Stückliste, Sprache: ### - Sprache: en" } ] } 

编辑:

我现在试过这个:

 $string = $this->input->post('requestdata'); var_dump($string); $json = preg_replace('/,\s*([\]}])/m', '$1', utf8_encode($string)); $json = json_decode($json); var_dump($json); 

结果是:

string(338)“{”projectnumber“:”4444“,”projecdescription“:”4444“,”articles“:[{”position“:1,”article_id“:676,”online_text“:”###Behälter; 乐队I-III nach indiv。 Stückliste,Sprache:DE – Sprache:de“},{”position“:2,”article_id“:681,”online_text“:”###Behälter; 乐队I-III nach indiv。 Stückliste,Sprache:### – Sprache:en“}]}”NULL

通过将JSON字符串直接粘贴到PHP源代码中,它可以正常工作,但不是从post中获取它!

由于字符串中的新行,您遇到错误

 $string = '{"projectnumber" : "4444","projecdescription" : "4444", "articles" : [{"position":1, "article_id" : 676, "online_text" : "### Behälter; Band I-III nach indiv. Stückliste, Sprache: DE - Sprache: de"},{"position":2, "article_id" : 681, "online_text" : "### Behälter; Band I-III nach indiv. Stückliste, Sprache: ### - Sprache: en"}]}'; $string = preg_replace("/[\r\n]+/", " ", $string); $json = utf8_encode($string); $json = json_decode($json); var_dump($json); 

产量

 object(stdClass)[1] public 'projectnumber' => string '4444' (length=4) public 'projecdescription' => string '4444' (length=4) public 'articles' => array 0 => object(stdClass)[2] public 'position' => int 1 public 'article_id' => int 676 public 'online_text' => string '### Behälter; Band I-III nach indiv. Stückliste, Sprache: DE - Sprache: de' (length=78) 1 => object(stdClass)[3] public 'position' => int 2 public 'article_id' => int 681 public 'online_text' => string '### Behälter; Band I-III nach indiv. Stückliste, Sprache: ### - Sprache: en' (length=79) 

投票换新线

json_decode_nice +保持换行符:

 function json_decode_nice($json, $assoc = TRUE){ $json = str_replace("\n","\\n",$json); $json = str_replace("\r","",$json); $json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','$1"$3":',$json); $json = preg_replace('/(,)\s*}$/','}',$json); return json_decode($json,$assoc); } 

如果你想保持换行符只是逃避斜线。

你不需要utf-8编码,如果一切都设置为utf-8(头,数据库连接等)

 $string = preg_replace("/[\r\n]+/", " ", $string); $json = utf8_encode($string); $json = json_decode($json); var_dump($json);