Warm tip: This article is reproduced from stackoverflow.com, please click
json php

SyntaxError: JSON.parse: expected when using a URL in json output

发布于 2020-03-31 22:57:11

I have a problem with when I watch JSON output with PHP containing a URL My code is as follows:

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

My output is then:

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

And this gives the error message:

SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 19 of the JSON data.

Do I change $url = "http://1.2.3.4:8080"; to $url = "test"; then it works.

How I can change this so that a URL also work?

Questioner
Colin
Viewed
25
mitkosoft 2020-01-31 19:55

Let play with the basics instead of re-inventing the wheel:

<?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);
?>

Output:

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

If you really have a new line somewhere in the string, you could escape it before adding the value into the JSON:

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

May the Force be with you.