Strange behaviour with asp.net and javascript array - javascript

This follows on from my question earlier about Visual Studio showing "" instead of ".
When I run the code below it creates a javascript array and returned as res[0] like below:
["Name","Name","Name"]
in visual studio it returns this:
"["Name","Name","Name"]"
When I run the code, this part shows the surrounding speech marks still (autocompletedata):
autocomplete(document.getElementById("rd-search-form-input"), autocompletedata );
This causes the code to not work. When i manually remove the surrounding double quotes, all works fine.
I've tried removing the start and end part of the string but it just removes the [ and ], which indicates that the string isn't surrounded by double quotes at all. I've also tried removing all double quotes but to no avail.
Can anyone explain whats going wrong?
var urlMethod = "/ajax.aspx/GetTeamMemberNamesList";
var params = new Object();
var result;
params.TeamID = 123;
result = SendAjaxSingleValue(urlMethod, params);
var res = result.d.split("|");
var autocompletedata = res[0];
autocompletedata.replace(/['"]+/g, '')
autocomplete(document.getElementById("rd-search-form-input"), autocompletedata );

To clarify the solution from the OP, the ajax call returns not the array itself but a JSON string, as is always the case when receiving data from a web server - hence why res[0] is returned as ["Name","Name","Name"].
Hence, in order to turn the response text into an actual array, it requires JSON.parse to perform the conversion.

Well, this was annoying - this fixed my issue:
autocomplete(document.getElementById("rd-search-form-input"), JSON.parse(autocompletedata));

Related

Generating fully valid JSON with client-side JavaScript

So I am trying to create a JSON explorer / editor. I am able to parse the initial JSON into the div and format it how I like.
this is the function i use to loop through the initial JSON
_iterate(_tab, raw_json){
var tab = _tab;
tab++;
for(var key1 in raw_json){
var data_type = typeof raw_json[key1];
var d = String(raw_json[key1])
if(d == String){
d = "String";
}
if(d == Number){
d= "Number"
}
if(data_type == "object" || data_type == "array"){
this.input.append(`<json-tab tab-width="${tab}"></json-tab><div class="json-editor-input-container-2 -je-${data_type}">'<span class="-je-key">${key1}</span>' :{</div></br>`)
this._iterate(tab, raw_json[key1])
}else{
this.input.append(`<div class="json-editor-row"><json-tab tab-width="${tab}"></json-tab><div class="json-editor-input-container-2">'<span class="-je-key">${key1}<span>' : '<div class="json-editor-input -je-${data_type}" contenteditable="true" for="{key: '${key1}', data: '${d}'}"></div>', </div></br></div>`)
}
}
this.input.append(`<json-tab tab-width="${tab -1}"></json-tab>},</br>`)
}
in order to save the JSON I was going to retrieve the JSON from the text of the div using
getJSON(){
var json_text = this.input.text().slice(0, -1)
return JSON.parse(`"${json_text}"`)
}
right now this is able to be parse by JSON.parse(); but when i want to console.log(getJSON()[0]) this returns {
am i not formating the JSON correctly. a live example of this can be found here
First, your console.log result doesn't make sense. A parsed JSON object is now usable in JavaScript and, if has (only) properties x and y, would result in undefined when requesting property 0 as you have. It looks like your call to console.log was to a different (earlier?) version of the getJSON() function, where it returned the raw string, and in that case it makes sense that you're just retrieving the first character of the JSON text: "{".
But then, assuming the version of getJSON() as written, it would actually throw a parse exception:
VM1511:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 1
Looking at your site, I was able to do, in the console:
jsonString = $('json-editor').text()
// value: "{'partName' : '', 'partRevision' : '', ..."
That is illegal JSON. JSON specifies (only) the quotation mark " for strings (Unicode/ASCII 0x22) on page 7 of its specification.
The fact that 'partName' is legal as a JavaScript string literal is irrelevant but perhaps confusing.
As a minor style point, simplify JSON.parse(`"${json_text}"`) to JSON.parse(json_text).
#BaseZen's answer was very helpful for me to understand what was going wrong with my code. My JSON was incorrectly formatted even though online linters say its correct. Along with what BaseZen pointed out, JSON.parse() will not work with trailing commas. To fix this:
_remove_trailing_commas(json_string){
var regex = /\,(?!\s*?[\{\[\"\'\w])/g;
return json_string.replace(regex, '');
}
I found this information at SO post JSON Remove trailiing comma from last object
SO user Dima Parzhitsky's answer was what helped me also figure out this question.

Creating object from JSON and parsing JSON - different results

I am trying to use JQuery to parse some JSON being sent back from an AJAX call. It appears to be failing to parse, and JSLint also says it's invalid JSON.
However, if I create the object directly, it works and I am able to loop through it - please see below:
var json = {layers:[{layer1:[17,16,15,14,12]}]}
alert(json)// <- This works and output object Object
var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"
var parsing = JSON.parse(somestring)
alert(parsing) // <- this doesn't and breaks on parse
// The below code will work provided the parsing is commented out
json.layers.forEach(function (outerObj)
{
Object.keys(outerObj).forEach(function (key)
{
outerObj[key].forEach(function (item)
{
alert(item)
});
});
});
I'm struggling to wrap my head around why it won't parse, but appears to work.
Edit
I realise by wrapping quotes around layers and layer1 fixes it, just not sure why it works one way - but not the other.
there is a difference between javascript object and JSON object, all keys of JSON object must be quoted.
var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"// not a valid json to parse, it is a normal string, you can use JSON.stringify() to make it a valid json identifiable string.
so the correct JSON string will look like
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}';
var parsedJson = JSON.parse(somestring)
If you change sometring to some of the following examples, it will works.
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'
var somestring = "{\"layers\":[{\"layer1\":[17,16,15,14,12]}]}"
The reason for this is, basically, that's how JSON was specified.
For further examples, take a look at w3schools
Best practice is to use JSON.stringify(Object) on one side, and JSON.parse(String) on the other. This will save you many hours of scratching your head over some niggling detail.
In your example, you could resolve the problem by
var somestring = JSON.stringify(json)
For future reference, however, JSON keys must be quoted, so your somestring should be written as:
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'
Good luck!

JSON.parse() returns wrong values for integers

[EDIT] I was modyfing the data later and it was reflected in the object when expanding it, I will accept my answer when I can.[/EDIT]
I've got a simple JSON string that needs parsing:
{"Points": [{"x": 0,"y": 33},{"x": 2200,"y": 28},{"x": 4400,"y": 23},{"x": 6600,"y": 20},{"x": 8800,"y": 19},{"x": 11000,"y": 18},{"x": 13200,"y": 17},{"x": 15400,"y": 15},{"x": 17600,"y": 13},{"x": 19800,"y": 12}]}
The string is generated by C++ code for graph drawing purposes. When I paste it into a json formatter it parses fine, giving proper values. The problem I'm facing are wierd Y values, for example the first object in array "Points" has y value of 20 - and there are no 20's anywhere in the string.
See attached picture, it explains everything. The code before what's on the picture is as follows:
RequestJSONParse: function(Data)
{
var Request = Data.split("|");
var RequestType = Request[0];
var RequestParams = Request[1];
var RequestData = undefined;
if (typeof Request[2] != "undefined" && Request[2] != "")
{
console.log("---");
console.log(Request[2]);
console.log("---");
RequestData = JSON.parse(Request[2]);
console.log("---");
console.log(RequestData);
console.log("---");
}
My question is - are the some special characters or a special way JSON.parse parses specifically x,y values? Or is this an encoding issue or something I can't even think of? I've been on this project for 2 years and didn't ever encounter anything like this and most of our UI is made by parsing JSON data.
Image explaining the problem
Check here your do like this
var json = "{\"Points\": [{\"x\": 0,\"y\": 33},{\"x\": 2200,\"y\": 28},{\"x\": 4400,\"y\": 23},{\"x\": 6600,\"y\": 20},{\"x\": 8800,\"y\": 19},{\"x\": 11000,\"y\": 18},{\"x\": 13200,\"y\": 17},{\"x\": 15400,\"y\": 15},{\"x\": 17600,\"y\": 13},{\"x\": 19800,\"y\": 12}]}";
var Request = json.split("|");
var data = JSON.parse(Request[0]);
console.log(data);
U can use above code if u r getting string in this way....
#JamesThorpe Was on point, I was modifying the object later and my changes were reflected in the object when it was expanded. The blue i symbol was the missing link for me.

App Inventor with Mysql and Javascript

A javascript issue again, I can't understand the problem. I use Appinventor to transfer a message to an html file using webviewstring. the message sent is here, starting with 1%mc:
As you can see, it jumps to the next line because everyline has an \n at the end.
In javascript, I try to create an array of arrays using this code:
var wvdata = window.AppInventor.getWebViewString().split('\n');
var urlArray = [];
for (var i in wvdata){
urlArray.push(wvdata[i].split('%'));
}
I don't know what's wrong with it, since it was running fine when I splitted it with a ,. Just because I need to use comma in some places, I changed my splitters to % but this doesn't work. I use script blocks like this one to assign data inside the array to items, but now it just shows the default data, as if there were nothing inside urlArray.
document.getElementById("testname0").innerHTML = urlArray[0][2];

Need to get an array of the names of all applicationScope variables

In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.

Categories

Resources