如何处理编码两次的JSON?

时间:2019-06-11 07:25:23

标签: php json

我有以下两组代码需要解码。

myArr = [{
    "id": 1,
    "msg": "Your Acct 123XXXX456 Has Been Debited with USD2,100.00 On 05- MAY - 2019 07: 26: 58 By AB: 123456 ** 7899 / USER NAME / 0505201. Bal: USD973 .28 CR "
  },
  {
    "id": 1,
    "msg": "Your Acct 123XXXX456 Has Been Debited with USD1,100.00 On 05 - MAY - 2019 07: 26: 58 By AB: 123456 ** 7899 / USER NAME / 0505201. Bal: USD673 .28 CR "
  },
  {
    "id": 2,
    "msg": "Your Acct 345XXXX678 Has Been Debited with USD4,100.00 On 05 - MAY - 2019 07: 26: 58 By AB: 11111 ** 22222 / USER NAME / 0505201. Bal: USD373 .28 CR "
  }
]

let result = myArr[0].replace(/\D+/g, ' ').trim().split(' ').map(e =>
  parseInt(e));
console.log(result)

对于第一个,尽管有效,但我完全无法对其进行解码。似乎“ question1”部分被编码了两次,我不知道这是怎么回事。

$test = 
'{
    "username":"sophia",
    "event":{
        "failure":"unreset",
        "answers":{
            "question1":"{\"answer\":\"{\\\"pass\\\":true,\\\"mark\\\":9,\\\"totalmark\\\":9,\\\"value\\\":\\\"get full attention|establish classroom rules|teach key words & concepts|use visual aids|demonstrate|check understanding|introduce point system|give handouts|play\\\"}\",\"state\":\"{\\\"result\\\":{\\\"pass\\\":true,\\\"mark\\\":9,\\\"totalmark\\\":9,\\\"value\\\":\\\"get full attention|establish classroom rules|teach key words & concepts|use visual aids|demonstrate|check understanding|introduce point system|give handouts|play\\\"}}\"}"
        }
    },
     "event_source":"server"
}';

对于第二个,我可以解码一次,但是$test = '{ "username":"lon", "event":{ "saved_response":"{\"parts\": [{\"text\": \"Passion for teaching means loving your job. Doing with all your heart. Teachers who are passionate can inspire pupils to love learning. Passionate teachers create an effective learning environment and increase learning potential of\\nstudents.\"}]}" }, "event_source":"server" }'; $jarray = json_decode($test, true); $jevent = json_decode($jarray['event']['saved_response'], true); 的输出为NULL。

任何人都可以向我解释为什么会发生这两个错误吗?我检查了How to deal with backslashes in json strings php,现在真的很困惑。 谢谢。

3 个答案:

答案 0 :(得分:2)

问题中的$test字符串不能正确反映您要解析的数据。您已经说过从日志中复制并粘贴了它,但是当您将包含反斜杠的文本粘贴到字符串文字中时,这些反斜杠不再是反斜杠,而是转义字符。您必须使用另一个反斜杠将其转义。也就是说,如果文本中包含testing\foo,并将其放入字符串文字中,则需要复制该反斜杠,以使文字创建其中包含相同文本的字符串:'testing\\foo'。 / p>

因此,为了准确反映您从日志复制的文本,$test文字应为:

$test = 
'{
    "username":"sophia",
    "event":{
        "failure":"unreset",
        "answers":{
            "question1":"{\\"answer\\":\\"{\\\\\\"pass\\\\\\":true,\\\\\\"mark\\\\\\":9,\\\\\\"totalmark\\\\\\":9,\\\\\\"value\\\\\\":\\\\\\"get full attention|establish classroom rules|teach key words & concepts|use visual aids|demonstrate|check understanding|introduce point system|give handouts|play\\\\\\"}\\",\\"state\\":\\"{\\\\\\"result\\\\\\":{\\\\\\"pass\\\\\\":true,\\\\\\"mark\\\\\\":9,\\\\\\"totalmark\\\\\\":9,\\\\\\"value\\\\\\":\\\\\\"get full attention|establish classroom rules|teach key words & concepts|use visual aids|demonstrate|check understanding|introduce point system|give handouts|play\\\\\\"}}\\"}"
        }
    },
     "event_source":"server"
}';

如您所说,question1是双重编码的。更糟糕的是,当您取消编码时,会发现它具有名为answerstate的属性,它们再次被 双重编码。

要全部取消编码,必须先对主位进行编码,然后question1,然后对其answerstate进行编码:

$obj = json_decode($test);
$obj->event->answers->question1 = json_decode($obj->event->answers->question1);
$obj->event->answers->question1->answer = json_decode($obj->event->answers->question1->answer);
$obj->event->answers->question1->state = json_decode($obj->event->answers->question1->state);

如果对转储到日志中的文本执行此操作,它将起作用。结果(来自var_dump)为:

object(stdClass)#1 (3) {
  ["username"]=>
  string(6) "sophia"
  ["event"]=>
  object(stdClass)#2 (2) {
    ["failure"]=>
    string(7) "unreset"
    ["answers"]=>
    object(stdClass)#3 (1) {
      ["question1"]=>
      object(stdClass)#4 (2) {
        ["answer"]=>
        object(stdClass)#5 (4) {
          ["pass"]=>
          bool(true)
          ["mark"]=>
          int(9)
          ["totalmark"]=>
          int(9)
          ["value"]=>
          string(161) "get full attention|establish classroom rules|teach key words & concepts|use visual aids|demonstrate|check understanding|introduce point system|give handouts|play"
        }
        ["state"]=>
        object(stdClass)#6 (1) {
          ["result"]=>
          object(stdClass)#7 (4) {
            ["pass"]=>
            bool(true)
            ["mark"]=>
            int(9)
            ["totalmark"]=>
            int(9)
            ["value"]=>
            string(161) "get full attention|establish classroom rules|teach key words & concepts|use visual aids|demonstrate|check understanding|introduce point system|give handouts|play"
          }
        }
      }
    }
  }
  ["event_source"]=>
  string(6) "server"
}

Live Copy

答案 1 :(得分:1)

您必须从第二个json中删除新行。

尝试一下:

trim(preg_replace('/\s+/', ' ',$jarray['event']['saved_response']))-多个空格和换行符替换为一个空格。

$test = 
'{
    "username":"lon",
    "event":{
        "saved_response":"{\"parts\": [{\"text\": \"Passion for teaching means loving your job. Doing with all your heart. Teachers who are passionate can inspire pupils to love learning. Passionate teachers create an effective learning environment and increase learning potential of\\nstudents.\"}]}"
    },
    "event_source":"server"
}';

$jarray = json_decode($test, true);
$jevent = json_decode( trim(preg_replace('/\s+/', ' ',$jarray['event']['saved_response'])), true);
var_dump($jarray);
var_dump($jevent);

https://3v4l.org/fnc1V

作为替代方案,您可以两次转义:

$test = 
'{
    "username":"lon",
    "event":{
        "saved_response":"{\\"parts\\": [{\\"text\\": \\"Passion for teaching means loving your job. Doing with all your heart. Teachers who are passionate can inspire pupils to love learning. Passionate teachers create an effective learning environment and increase learning potential of\\\\nstudents.\\"}]}"
    },
    "event_source":"server"
}';

$jarray = json_decode($test, true);
$jevent = json_decode( $jarray['event']['saved_response'], true);
var_dump($jarray);
var_dump($jevent);

https://3v4l.org/9k3t1

How do I handle newlines in JSON?

答案 2 :(得分:0)

这将解码损坏的json字符串。

$test = 
'{
    "username":"lon",
    "event":{
        "saved_response":"{\"parts\": [{\"text\": \"Passion for teaching means loving your job. Doing with all your heart. Teachers who are passionate can inspire pupils to love learning. Passionate teachers create an effective learning environment and increase learning potential of\\nstudents.\"}]}"
    },
    "event_source":"server"
}';

var_dump(json_decode(preg_replace('/[\x00-\x1F\x80-\xFF]/', '', json_decode($test, true)['event']['saved_response']), true)['parts'][0]['text']);