Correct JS parse of URL transmitted via JSON - javascript

Here's a 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);
};
That throws the following error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
If I substitute JSON.parse(this.responseText) with decodeURI(this.responseText), I get cleanedText equal to
/home/ubuntu/CANE-HDD-100/y.txt
["%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt"]
which I dislike, since an hypotetic for loop on cleanedText would treat every element of that variable (correctly) as a character, while I'd obviously like to get elements as whole URLs.
A possible, dirty workaround is to set up some regex on cleanedText to recover every URL, but I'm wondering if there would be a much cleaner way.

w3re's comment has to be correct. You must have malformed JSON. We can show this by taking the output you do get from decodeURI, running it back through encodeURI to get what must therefore be your original string from PHP, and then trying JSON.parse on it. 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 /
That error is from Chrome, but the :1 is saying 'line 1' and the / is at column 1, so I think that's the error you're seeing.
Basically, this string is not valid JSON, because of the all the stuff at the start which is not wrapped in quotes.
However, for example, this will work, if you put it all 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 an object:
JSON.parse('{"/home/ubuntu/CANE-HDD-100/y.txt": "%2Fhome%2Fubuntu%2FCANE-HDD-100%2Fy.txt"}')
so something must be going awry in your PHP or JavaScript in and amongst your JSON encoding and decoding. To help further, I'd need to see more of your code.

Related

JSON parse double quotes

I encountered a very strange error. If I run JSON.Parse('[""d""]') then I have error: "Unexpected token d in JSON at position 3"
JSON.parse('["\"d\""]')
If I run console.log(JSON.stringify(['"d"'])) then I get '[""d""]'
console.log(JSON.stringify(['"d"']))
If I run console.log(JSON.parse(JSON.stringify(['"d"']))) then I get good result [""d""]
console.log(JSON.parse(JSON.stringify(['"d"'])))
If I use eval function then I have error: "Uncaught SyntaxError: Unexpected token d in JSON at position 3"
var someJson=JSON.stringify(['"d"']);
window.eval(`JSON.parse('${someJson}')`)
How fix it?
I use some external library and there is window.eval(JSON.parse('${JSON.stringify(t)}'))). Where t - json array with strings. String can contains double quoutes. It throws exception.
I found js changed my string value when I set it.
var someJson='["\"d\""]';
console.log(someJson);
It returns '[""d""]' and when I run JSON.Parse it is incorrect JSON.
How fix it?
JSON.parse('["\"d\""]')
\ is a special character in JS strings, so to include it in your JSON you need to escape it.
const yourString = '["\"d\""]';
const validJSON = '["\\"d\\""]'
const parsedData = JSON.parse(validJSON);
document.querySelector('#yourString').value = yourString;
document.querySelector('#validJSON').value = validJSON;
<p>Your string: <output id="yourString"></output>
<p>Valid JSON: <output id="validJSON"></output>
As a rule of thumb, embedding JSON in string literals is a waste of time and effort. You can just write the JS data structure you get from parsing the JSON.
#Quentin many thanks for idea! Result answer for me:
var someJson=JSON.stringify(['"d"']);
console.log(window.eval(`JSON.parse('${someJson.replaceAll('\\','\\\\')}')`))

Parsing encoded php object having a property containing html markup

I need to json encode a php object called 'contact' in my controller, pass it to my view and then parse it using javascript. One of the object properties contains HTML markup, which seems to cause a lot of issues. I have been running in to a lot of trouble successfully parsing the object.
I keep getting the following javascript error when calling JSON.parse().
VM4464:1 Uncaught SyntaxError: Unexpected token & in JSON at position 1
at JSON.parse (<anonymous>)
What I tried:
PHP
$contact = htmlspecialchars(json_encode($contact), ENT_QUOTES, 'UTF-8');
Front end
var contact = JSON.parse("{{ $contact }}");
just yesterday I had the same problems, apparently it has something to do with blade escaping special character. I found the answers on this site,
try
var contact = JSON.parse('{!! json_encode($contact) !!}');
notice the use of {!! instead of {{, and try to experiment the usage of single/double quotes, or even without quotes, maybe?

JSON to JavaScript, SyntaxError: Unexpected token &

I know this question has been asked numerous times, but I really donĀ“t get it.
I am creating a site in MVC, and I'm creating a JSON string from my model. I then want to pass it as argument to a JavaScript function that uses it to plot a graph.
Here is were I create the JSON string. This indeed creates a valid JSON string, I checked it at JSONLint.
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var weightsAsJsonString = serializer.Serialize(Enumerable.Select(Model, weight =>
new
{
date = weight.Date,
value = weight.Value
}));
}
Further down I create a JavaScript variable from it and pass it into the JavaScript function:
var jsonStringToGraph = #weightsAsJsonString;
google.setOnLoadCallback(drawVisualization(jsonstring));
When I run this, the console prints 'SyntaxError: Unexpected token &' at the line were I declare jsonStringToGraph. I googled around and concluded that I should put ' ' around #weightsAsJsonString, so I do that.
Anyway, in my drawVisualization, I do this:
function drawVisualization(teststring) {
.......
var parsedJson = JSON.parse(teststring);
This gives me SyntaxError: Unexpected token & Index:1
I know that the code at the bottom is what is causing the exception, but I do not understand why. Do anyone understand what I am doing wrong?
Edit: This is the weightsAsJsonString
[{"date":"\/Date(1434492000000)\/","value":100.2},{"date":"\/Date(1434578400000)\/","value":99.2},{"date":"\/Date(1434664800000)\/","value":101.2},{"date":"\/Date(1434751200000)\/","value":98.2},{"date":"\/Date(1434837600000)\/","value":97.2},{"date":"\/Date(1434924000000)\/","value":96.2},{"date":"\/Date(1435010400000)\/","value":95.2},{"date":"\/Date(1435096800000)\/","value":94.2}]
It sounds like your issue is trying to inject content via Razor into JavaScript. By default # will HTML-encode your content, which doesn't work in the context of JavaScript.
#Html.Raw(weightsAsJsonString) will work better, and then your JS will have a JavaScript object, so there's no need for the JSON.parse later on.
When you do var jsonStringToGraph = #weightsAsJsonString; you are actually defining a JSON object and not a JSON string.
Hence when you do JSON.parse(teststring); you are trying to parse an object instead of a string.
Either put apostrophes around the first declaration var jsonStringToGraph = '#weightsAsJsonString'; or simply do not try to parse it again.

How to solve "Unterminated string literal" error while using JSON.parse method?

I get JSON data from the Yandex.Direct API, but when I try to parse it there is an error:
SyntaxError: Unterminated string literal (line 231, file
"importJSON")
My code:
var jsondata = UrlFetchApp.fetch('https://api.direct.yandex.ru/v4/json/', options);
var contextText = jsondata.getContentText();
var object = JSON.parse(contextText);
I think that this problem may be caused by invisible symbols U+2028, U+2029 (http://timelessrepo.com/json-isnt-a-javascript-subset), but I can't find it in the result file.
Please share any suggestions.
UPDATE: I cannot post the resulting JSON here because it contains sensitive production data.
The error appears when using the method
http://api.yandex.ru/direct/doc/reference/GetBanners.xml - 1 request with 10 campaign_ids = [8388422,8396871,8409767,8409910,8409979,8434877,8434885,8434891,8435993,8446636];
If I use this method ten times with one campaign_id in the request, there is no such problem. It's very strange.

strange javascript behavior - JSON.parse: unexpected character

i have the following button :
<button onclick='enroll(<?php echo $course['cs_id']; ?>)'>enroll</button>
when the user click on it the following javascript function will start :
function enroll(id){
$.post("<?php echo base_url().'courses/enroll/'; ?>"+id , function(data){
obj = JSON.parse(data);
alert(obj.state);
});
}
which perform a post request to php page which echo json array like this :
$data = array("state"=>"done");
die(json_encode($data));
but unfortunately the following error appears in the console :
JSON.parse: unexpected character
i checked the page response and its look like this (which seems fine ) :
{"state":"done"}
also when i change the enroll() function to be like this :
function enroll(id){
$.post("<?php echo base_url().'courses/enroll/'; ?>"+id , function(data){
alert(data);
});
}
its show the alert message correctly like this :
{"state":"done"}
so why it refuse do parse the response where everything seems okay ? any idea ?
My guess is that your code is actually working better than you think! I think that jQuery receives your JSON from the server and realises that it is JSON, even though you haven't specified it as such. (Perhaps your PHP is sending a Content-Type header?)
So data is actually already a Javascript object, which jQuery has decoded from your JSON. When you call JSON.parse on an object, it is converted to a string [object Object], and then parsed. [object Object] is evidently invalid JSON, hence the unexpected character error.
Since the string was obviously valid JSON, my next guess was that there was some data before the string that was causing the parser to be unhappy. The best way to test this is with String#charCodeAt, which reveals the precise character at a given point in the string.
So, with the following code, we can test to see what the first character in the string is:
console.log(data.charCodeAt(0));
You say that this returns 65279, which, at the beginning of a Unicode document, is a byte order mark. You are apparently outputting this somewhere in your server-side code. You need to find out where that is and remove it.
Do not parse the data again:
function enroll(id){
$.post("<?php echo base_url().'courses/enroll/'; ?>"+id , function(data){
alert(data.state);
});
}

Categories