首页 > 解决方案 > SyntaxError:JSON.parse:在 json 输出中使用 URL 时需要

问题描述

当我使用包含 URL 的 PHP 观看 JSON 输出时遇到问题我的代码如下:

 <?php
   $url = "http://1.2.3.4:8080";
   Header('Content-type: application/json');
 ?>{"status" : "URL" : "<?php echo $url ?>"}

我的输出是:

 {"status" : "URL" : "http://1.2.3.4:8080
 "} 

这给出了错误消息:

SyntaxError: JSON.parse: 在 JSON 数据的第 1 行第 19 列的对象中的属性值之后预期为“,”或“}”。

我是否更改$url = "http://1.2.3.4:8080";$url = "test";然后它可以工作。

我如何更改它以使 URL 也可以工作?

标签: phpjson

解决方案


让我们玩基础知识,而不是重新发明轮子:

<?php
    $url = "http://1.2.3.4:8080";
    Header('Content-type: application/json');
    $arr = array('status'=>'success', 'url'=>$url);
    echo json_encode($arr, JSON_UNESCAPED_SLASHES);
?>

输出:

{"status":"success","url":"http://1.2.3.4:8080"}

如果字符串中确实有新行,则可以在将值添加到 JSON 之前对其进行转义:

$url = str_replace(array("\r\n", "\n", "\r"), "", $url);

愿原力与你同在。


推荐阅读