【问题标题】:PHP 7.2 json_decode()PHP 7.2 json_decode()
【发布时间】:2018-11-27 08:26:40
【问题描述】:

我有这个字符串可以在 PHP 5.6 中使用 json_decode() 但不适用于 PHP 7.2

$json = '
{
  "text": "Hi {{fname}} 
   Welcome to our customer support. 
   Please select language to proceed",
  "buttons": [
    {
      "text": "English",
      "value": "language_english",
      "type": "postback"
    },
    {
      "text": "Germany",
      "value": "language_germany",
      "type": "postback"
    }
  ]
}';

我尝试过像这样替换空格和换行符

$json = preg_replace("/\n/m", '\n', $json);
$what   = "\\x00-\\x19"; // all whitespace characters except space itself
$json = trim(preg_replace( "/[".$what."]+/" , '' , $json));

这会变成这样的字符串

\n{\n  "text": "Hi {{fname}} \n   Welcome to our customer support. \n   Please select language to proceed",\n  "buttons": [\n    {\n      "text": "English",\n      "value": "language_english",\n      "type": "postback"\n    },\n    {\n      "text": "Germany",\n      "value": "language_germany",\n      "type": "postback"\n    }\n  ]\n}

注意双引号之间和外部的\n,这使它成为无效的json,因此json_decode在这种情况下不起作用。

有谁知道实现这一目标的方法吗?

谢谢。

【问题讨论】:

标签: php json php-5.6 php-7.2


【解决方案1】:
{
    "text": "Hi {{fname}} \n Welcome to our customer support. \n Please select language to proceed",
    "buttons": [{
            "text": "English",
            "value": "language_english",
            "type": "postback"
        },
        {
            "text": "Germany",
            "value": "language_germany",
            "type": "postback"
        }
    ]
}

这是一个有效的 json。我添加了换行符,因此如果您想在浏览器中打印消息,可以使用它们。

当您有疑问时,您可以使用这个漂亮的tool 来验证您的 json。

根据评论反馈编辑我的答案。

首先正确的步骤是弄清楚为什么数据库中有损坏的 json。如果它不在你身上,你必须在 php 中修复它,那么解决方案可能是这样的:

<?php
echo '<pre>';
$data = '
{
  "text": "Hi {{fname}} 
   Welcome to our customer support. 
   Please select language to proceed",
  "buttons": [
    {
      "text": "English",
      "value": "language_english",
      "type": "postback"
    },
    {
      "text": "Germany",
      "value": "language_germany",
      "type": "postback"
    }
  ]
}';


        if (strstr($data, "\n")) {
            $data = trim(preg_replace('/\s\s+/', '  ', $data));
        }

        echo $data;

以上代码将捕获文本字段的换行符,并将其替换为 DOUBLE 空格。然后你会得到一个有效的json,比如:

{
"text": "Hi {{fname}}  Welcome to our customer support.  Please select language to proceed",
"buttons": [
{
"text": "English",
"value": "language_english",
"type": "postback"
},
{
"text": "Germany",
"value": "language_germany",
"type": "postback"
}
]
}

如果您需要换行符,您可以做的是解码您的 json(就像您想要的一样,并用换行符替换 text 字段中的双倍间距

【讨论】:

  • 嗨@pr1nc3。上面发布的json字符串原样来自数据库。
  • 那么你应该检查为什么你的数据库中有无效的 JSON。
  • 编辑了我的帖子。正如我在我编辑的帖子中提到的那样,仅当您无法修复 json 以便以有效格式检索它时才建议使用此解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 2011-05-03
  • 2018-01-30
  • 2016-09-20
  • 1970-01-01
相关资源
最近更新 更多