小编典典

带有特殊字符的Json_decode

json

我遇到了一个大问题,即通过jQuery Ajax将数据作为JSON发布到我的服务器。JSLint表示数据正常,并且请求的Content-
Type设置为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是发布数据:$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乐队个人。Stückliste,语言:DE-语言:de“},{” position“:2,” article_id“:681,”
online_text“:” ###Behälter; I-III乐队个人。Stückliste,语音:###-语音:en“}]}” NULL

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


阅读 316

收藏
2020-07-27

共1个答案

小编典典

您由于字符串中的新行而出错

$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)
2020-07-27