php - 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 也可以工作?
解决方案
让我们玩基础知识,而不是重新发明轮子:
<?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);
愿原力与你同在。
推荐阅读
- swift - 在 Perform Segue 上传递参数返回 nil
- c++ - 在 Windows 中通过 Eclipse 使用 CMake 的 LibTorch:终止退出值 390
- swift - 无法获取 SavedPost
- python - 如何根据屏幕分辨率适配使用 PyQt5 开发的 GUI?
- api - 如何在 Zabbix API 中搜索主机组
- javascript - Unicode 代理对和 String.fromCodePoint() — JavaScript
- java - 如何将我的多行输出转换为 3x4
- php - PHP - 如何在换行符之前使用“>”删除换行符
- python - 在创建的文件中添加文本
- php - HTTP:状态 405:url:'http://mydashboard/mybi/gateway.php''