Unable to parse valid json file - javascript

Logic
I've a JSON file as follows:
[
{
"title":"Article Title 1",
"url":"https://mywebsite.com/articles/article1.html",
"type":"codes"
},
{
"title":"Article Title 2",
"url":"https://mywebsite.com/articles/article2.html",
"type":"games"
},
{
"title":"Article Title 3",
"url":"https://mywebsite.com/articles/article3.html",
"type":"codes"
}
]
And I'm reading this file, then populating my html page for each item in the file (so there are 3 titles, means 3 containers on my page).
Problem
There was no error before, but now I get an error in console: *SyntaxError: JSON.parse: expected ',' or ']' after array element at line 12 column 2 of the JSON data*
BUT, it all works if there are only 2 articles! After adding the third dataset, there is error. The file format seems correct, there is "," at the right places, I converted it in different encodings but same error.
Code
Main Request:
I'm requesting JSON file on document load like this:
$(document).ready(function(){
var reqdata = new XMLHttpRequest();
reqdata.open('GET', "https://website.com/dat/data.json");
reqdata.onload = function() {
if (reqdata.status >= 200 && reqdata.status < 400) {
try{
var postData = JSON.parse(reqdata.responseText);
render_posts(postData); // this creates dynamic content in html
//console.log(postData);
} catch (err) {
alert(" JSON Parse Error :'( ")
}
} else { alert("JSON Requestion Server Error!") }
}; reqdata.onerror = function() { alert("JSON Request Connection Error!") };
reqdata.send();
});
Populating HTML:
This is called from the code above if JSON.parse is working. This part works fine, just for reference..
function render_posts(data) {
var htmldata = ""; var cardId = "";
for (var x = 0; x < data.length; x++) {
cardId = "card-type-" + data[x].type;
htmldata += "<div class='card' id='" + cardId + "' onclick='card_clicker(\"" + data[x].url + "\")'><div class='header'>" + data[x].title + "</div><div class='decor'></div></div>";
}
cardWrapper.insertAdjacentHTML('beforeend', htmldata);
}
Help: Any help is appreciated.. Can't figure out what's the real problem. The JSON file looks fine. I tried formatting it online, but same results. I'm quite new to AJAX. Tried other solutions on stackoverflow but still the same..

It's a small url decoding problem with JSON decode. Instead of adding the url like:
"url":"https://mywebsite.com/articles/article2.html"
It has to be given escape character backslash like this:
"url":"https:\/\/mywebsite.com\/articles\/article2.html"
And now everything is working fine!

Probably hard to notice extra characters somewhere
or
non-standard double quotes used
or
some other character that is not as you think it is (comma?)

Related

How to loop through ViewData with Javascript in ASPX View

I have populated ViewData item with an array of questions so that I can store the json data in local storage:
string[] jsonQuestions = new string[StudentExam.QuestionCount];
for (int i = 0; i < StudentExam.QuestionCount; i++)
{
jsonQuestions[i] = new JavaScriptSerializer().Serialize(StudentExam.QuestionsE[i]);
ViewData[i.ToString()] = jsonQuestions[i];
}
During testing I loaded the ViewData into the localstorage like this (hard coded) for the exact amount of questions:
localStorage.setItem("obj0", JSON.stringify(<%=ViewData["0"]%>));
localStorage.setItem("obj1", JSON.stringify(<%=ViewData["1"]%>));
localStorage.setItem("obj2", JSON.stringify(<%=ViewData["2"]%>));
localStorage.setItem("obj3", JSON.stringify(<%=ViewData["3"]%>));
//...etc.
In the view I am trying to now dynamically load the ViewData into the browser localstorage like this using javascript:
<script>
var mod = "<%=Html.Raw(Model.TotalNumberOfQuestionsForTest.ToString())%>";
for (var i = 0; i < mod; i++) {
localStorage.setItem(
"obj" + i.toString(),
JSON.stringify(<%=ViewData[i.toString()]%>));
};
</script>
Now this gave me an error that it cannot find i, since we "escaped" the client side code. So I changed it to :
for (var i = 0; i < mod; i++) {
var s = <%=ViewData[%>i.toString()<%]%>;
localStorage.setItem(
"obj" + i.toString(),
JSON.stringify(<%=ViewData[%>i.toString()<%]%>));
};
This is the part where I'm stuck at. I keep getting these errors on this line:
JSON.stringify(<%=ViewData[%>i.toString()<%]%>));
Error 7 Invalid expression term ';'
and
Error 8 ; expected
and when I run the web app this is all I get on inspect element:
Compilation Error
Description: An error occurred during the compilation of a resource
required to service this request. Please review the following specific
error details and modify your source code appropriately.
Compiler Error Message: CS1525: Invalid expression term ')'
Source Error:
Line 278: localStorage.setItem( Line 279:
"obj" + i.toString(), Line 280:
JSON.stringify(<%=ViewData[%>i.toString()<%]%>)); Line 281: Line 282:
};
Is there a way to escape the <%%> tags, into the javascript again for the javascript variable to use in the ViewData? Or another way to do this?
UPDATE:
I went on and played around with the code a bit more and this is the closest I have gotten to what I need to happen by doing it like this:
$(function () {
<% for (int i = 0; i < 1; i++){%>
<%="localStorage.setItem('obj" + i.ToString() + "',JSON.stringify('"%><%=ViewData[i.ToString()]%>"'))"
<%}%>
});
So this does loop through my questions and put the value in where I needed, but the last issue I have is that now by having to put the javascript in quotations :
<%="localStorage.setItem('obj" + i.ToString() + "',JSON.stringify('"%><%=ViewData[i.ToString()]%>"'))"
The last quotation mark is needed to close the string between the <%%> tags. but this quotation mark is giving me the error:
Invalid or unexpected token
as my javascript to store the localstorage looks like this now:
localStorage.setItem("obj1", JSON.stringify("my json query"))" //this quotation is the problem
Any assistance or help will be greatly appreciated.
I finally fix the problem. The issue with the quotation was that I was "stringifying" a string and the moment I removed the single quotation marks from the code:
$(function() {
<% for (int i = 0; i < Model.TotalNumberOfQuestionsForTest; i++){%>
<%="localStorage.setItem('obj" + i.ToString() + "',JSON.stringify("%>
<%=ViewData[i.ToString()]%>
<%="))"%>
<%}%>
The json object was successfully stored in the localstorage of the browser.

GoogleTagManager do not seem to accept base64 encoded picture

Is it me or GoogleTagManager do not seem to accept base64 encoded pictures?
Exemple with the very basic code below with a very basic image.
I get the following error :
- Type : JavaScript Too Long"
- Description :
"The JavaScript in your Arbitrary HTML tag has too many contiguous non-whitespace characters (e.g. an array literal '[1,2,..]' that is too long). Try inserting spaces between statements to allow compilation (e.g. change '[1,2,...]' to '[1, 2, ...]')."
Is there no way to implement this in GTM, beside putting the js somewhere else than directly into GTM?
Best,
J.
<script type="text/javascript">
var myurl = "http://wwww.toto.com";
var myimg = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCACYAMoD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6bVgi3ITq42XhID+PBl1t6NCBm9rujr25d/Q2Oa4iImbHZELsB8FrSoL8T0lp1aZ8Gp+Pur+QOZezco+UIiyhUkMfFqw52Ja1VVCtKrKjaXm5hsK/IUhnzow4+cCpbVo3xz1OrC66zsGnrKjim8u0hry0oZI6+nLD1d9hLTemrs8xKWNrQ/tfDmzODe7N/K5vwcLWxcjXpv5qVThy99xwDT6W4+l0NnQNYqPZoboJYXZCBNOzsRu/26q7+qu/2ZuPKONHoErOvdqd5FVVf3q0u0kP1X59CTrGr/AO3VVd/v3AAKMtQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARP/Z";
$("#beta-ad").empty();
$('<div/>', { id: "1" }).insertBefore($("#beta-ad"));
$("#1").append('<img src="' + myimg + '" style="display:inline; width: auto;" ></img>')
</script>
I think this is by design. But the workaround proposed by #Matus works.
To get around the issue of having to generate JS for a very long base base 64 encoded string I wrote a utility function, splitting the string into chunks of 150 (which GTM accepts), and generating the JS concatenation code.
You can then drop this code into your GTM tag, and reference the base64 variable.
function splitString(string, size, multiline) {
var matchAllToken = (multiline == true) ? '[^]' : '.';
var re = new RegExp(matchAllToken + '{1,' + size + '}', 'g');
var responses = string.match(re);
var value = "var base64='';";
responses.forEach(response => {
value += "base64+='" + response + "';";
});
return value;
}
var base64 = 'eyJ3aWRnZXRfc2.... etc';
var gtmString = splitString(base64, 150, true);
console.log(gtmString);
http://jsfiddle.net/azqpdwxg/2/

Javascript Web API JSON Parsing Format issue

Hi i have an issue with a few lines of code in JS and formatting my JSON data. Basically in my DB i have a field that is set to nchar(10) but some of the data in the fields are for example only 8 characters long.
The problem i have is when my JS generates a link from JSON data it attaches Spaces to the Data to compensate the (10) characters. For example clicking a link generated from the JS Would generate a link for me like this http://....api/Repo/rep10016
In my JSON it passes in this data
rep10016
But my JS is grabbing this data for the link adding spaces up to 10 as it is a nchar(10) like this.
repoCode = "rep10016 "
But i only want
repoCode = "rep10016"
My JS Code
function displayRepos(repo) {
var table = document.getElementByrCode("rList");
table.innerHTML = "";
for (var i = 0; i < arr.length; i++)
{
var rCode = arr[i].repoCode;
cell2.innerHTML = "<a href='#'rCode='" + rCode + "' " + " >Repo List</a>";
document.getElementByrCode(rCode).onclick = getRepo;
}
function getRepo(rep)
{
var repoUrl = genUrl+rep.target.rCode+"?code="+rep.target.rCode;
......
}
The repoUrl variable is generating a link like this
"http://....api/Repo/rep10016 ?code=rep10016 /"
How can i get my code to only take the actual data and not format it to the nchar(10) format that is in my db??
repoCode.trim() will do the trick.
I would use string.trim();
var orig = 'foo ';
console.log(orig.trim()); // 'foo'

Display thumbnailPhoto from Active Directory using Javascript only - Base64 encoding issue

Here's what I'm trying to do:
From an html page using only Javascript I'm trying to query the Active Directory and retrieve some user's attributes.
Which I succeded to do (thanks to some helpful code found around that I just cleaned up a bit).
I can for example display on my html page the "displayName" of the user I provided the "samAccountName" in my code, which is great.
But I also wanted to display the "thumbnailPhoto" and here I'm getting some issues...
I know that the AD provide the "thumbnailPhoto" as a byte array and that I should be able to display it in a tag as follow:
<img src="data:image/jpeg;base64," />
including base64 encoded byte array at the end of the src attribute.
But I cannot manage to encode it at all.
I tried to use the following library for base64 encoding:
https://github.com/beatgammit/base64-js
But was unsuccesful, it's acting like nothing is returned for that AD attribute, but the photo is really there I can see it over Outlook or Lync.
Also when I directly put that returned value in the console I can see some weird charaters so I guess there's something but not sure how it should be handled.
Tried a typeof to find out what the variable type is but it's returning "undefined".
I'm adding here the code I use:
var ADConnection = new ActiveXObject( "ADODB.connection" );
var ADCommand = new ActiveXObject( "ADODB.Command" );
ADConnection.Open( "Data Source=Active Directory Provider;Provider=ADsDSOObject" );
ADCommand.ActiveConnection = ADConnection;
var ou = "DC=XX,DC=XXXX,DC=XXX";
var where = "objectCategory = 'user' AND objectClass='user' AND samaccountname='XXXXXXXX'";
var orderby = "samaccountname ASC";
var fields = "displayName,thumbnailPhoto";
var queryType = fields.match( /,(memberof|member),/ig ) ? "LDAP" : "GC";
var path = queryType + "://" + ou;
ADCommand.CommandText = "select '" + fields + "' from '" + path + "' WHERE " + where + " ORDER BY " + orderby;
var recordSet = ADCommand.Execute;
fields = fields.split( "," );
var data = [];
while(!recordSet.EOF)
{
var rowResult = { "length" : fields.length };
var i = fields.length;
while(i--)
{
var fieldName = fields[i];
if(fieldName == "directReports" && recordSet.Fields(fieldName).value != null)
{
rowResult[fieldName] = true;
}
else
{
rowResult[fieldName] = recordSet.Fields(fieldName).value;
}
}
data.push(rowResult);
recordSet.MoveNext;
}
recordSet.Close();
console.log(rowResult["displayName"]);
console.log(rowResult["thumbnailPhoto"]);
(I replaced db information by Xs)
(There's only one entry returned that's why I'm using the rowResult in the console instead of data)
And here's what the console returns:
LOG: Lastname, Firstname
LOG: 񏳿က䙊䙉Āā怀怀
(same here Lastname & Firstname returned are the correct value expected)
This is all running on IE9 and unfortunetly have to make this compatible with IE9 :/
Summary:
I need to find a solution in Javascript only
I know it should be returning a byte array and I need to base64 encode it, but all my attempts failed and I'm a bit clueless on the reason why
I'm not sure if the picture is getting returned at all here, the thing in the console seems pretty small... or if I'm nothing doing the encoding correctly
If someone could help me out with this it would be awesome, I'm struggling with this for so long now :/
Thanks!

Javascript syntax error

Update: I tried a version of the script without the "beforeContentUpdate" part, and this script returns the following JSON
{"COLUMNS":["TNAME","TBRIEF","GAMEID","TITLEID","RDATE","GNAME","PABBR","PNAME","RSCORE","RNAME"],
"DATA":[["Dark Void","Ancient gods known as 'The Watchers,' once banished from our world by superhuman Adepts, have returned with a vengeance.",254,54,"January, 19 2010 00:00:00","Action & Adventure","X360","Xbox 360",3.3,"14 Anos"]]}
Using the script that includes "beforeContentUpdate," however, returns nothing. I used Firebug to see the contents of the div generated by the tooltip, and it's blank!
Hello, I'm wondering if anyone can help me with a syntax error in line 14 of this code:
The debugger says missing ) in parenthetical on var json = eval('(' + content + ')');
// Tooltips for index.cfm
$(document).ready(function()
{
$('#catalog a[href]').each(function()
{
$(this).qtip( {
content: {
url: 'components/viewgames.cfc?method=fGameDetails',
data: { gameID: $(this).attr('href').match(/gameID=([0-9]+)$/)[1] },
method: 'get'
},
api: {
beforeContentUpdate: function(content) {
var json = eval('(' + content + ')');
content = $('<div />').append(
$('<h1 />', {
html: json.TNAME
}));
return content;
}
},
});
});
});
You forgetting a
+
Should be:
var json = eval('(' + content + ')');
the best for this is www.jslint.com
i'd copied and paste your code and show me this:
Problem at line 21 character 10: Extra
comma.
},
Make sure you JSON has no extra characters, the JSON must be valid. Check how the content returns with a plain alert so nothing will change the string.
Also, consider using parseJSON from jQuery instead of eval. Quote:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
This turned out to be another case where the ColdFusion debugger, when request debugging output is turned on, causes an ajax error. This is one big "gotcha" we need to remember when working with ColdFusion with debugging enabled. It breaks down ajax.

Categories

Resources