Fix JS parsing of url passed through JSON

Here's the simplified PHP side of my ajax context:

// in a for loop
    $text = "/home/ubuntu/CANE-HDD-100/y.txt"
    // $text_encoded = urlencode($text);
    // $text_encoded = preg_replace("/(\-)/", "%2D", $text_encoded);
    $text_encoded = "%2Fhome%2Fubuntu%2FCANE%2DHDD%2D100%2Fy.txt"
    $structure[$i] = $text_encoded;

echo json_encode($structure);

      

And here is the JS side:

request.onload = function()
{
    var cleanedText = JSON.parse(this.responseText);
    alert(cleanedText);
};

      

This throws the following error:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of JSON data

If substituted JSON.parse(this.responseText)

for decodeURI(this.responseText)

, I get cleanedText

equal to

/home/ubuntu/CANE-HDD-100/y.txt ["% 2Fhome% 2Fubuntu% 2FCANE-HDD-100% 2Fy.txt"]

which I do not like, because the hypothetical cycle for

to cleanedText

be processed every element of this variable (correctly) as a symbol, while I obviously would like to get the items as the whole URL-addresses.

A possible, dirty workaround is to set up some regex on cleanedText

to recover each url, but I'm wondering if there would be a cleaner way.

+3


source to share


1 answer


W3re's comment must be correct. You must have incorrect JSON. We can show this by taking the output you get from decodeURI

, running it back through encodeURI

to get what your original string should be from PHP, and then trying it JSON.parse

on. We get an error:

JSON.parse(encodeURI('/home/ubuntu/CANE-HDD-100/y.txt ["%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt"]'))
(program):1 Uncaught SyntaxError: Unexpected token /

      

This error is from Chrome, but it :1

says "line 1" and it /

is in column 1, so I think that is the error you are seeing.

Basically, this string is not valid JSON, because all things at the beginning that are not quoted.

However, for example this will work if you put the whole thing in quotes and escape the existing ones:

JSON.parse('"/home/ubuntu/CANE-HDD-100/y.txt \\"%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt\\""')

      



or using an array:

JSON.parse('["/home/ubuntu/CANE-HDD-100/y.txt", "%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt"]')

      

or object:

JSON.parse('{"/home/ubuntu/CANE-HDD-100/y.txt": "%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt"}')

      

so something must be wrong in your PHP or JavaScript inside and among your JSON encoding and decoding. To help further, I will need to see more of your code.

0


source







All Articles