split() is not giving the expected outcome - javascript

I'm having problems why my .split() function.
somehow when i splay my line the first [0] element in the array can be accessed but the 2nd [1] can't
I have the following string:
,{"relationID":"000001","recID":"1d2712eb-4f08-4b4f-b6e9-600c9631b503"
And the code below is how i try to split this (tempArray contains a x number of strings like the above):
var templine = tempArray[i].substr(1, tempArray[i].length);
//alert(templine);
var line = templine.split(',');
var s1 = line[0].split('"')[3];
var s2 = line[1].split('"')[3];
when i use alert(s1) or alert(s2) i do get the value however, the folowing error always occurs on the last line (var s2):
caught TypeError: Cannot read property 'split' of undefined
this causes the rest of my script to crash and it won't finish what it's supposed to, displaying an empty page.
My question, what is going wrong here? why does s1 function properly and s2 which is exactly the same except for the index of the line array crash my script.
I want to emphasise when i use the alert function to check the value of my variable s1 and s2 they do contain the right value.
EDIT:
maybe a nice bonus since there might be an easyer way.
after I've gotten the values s1 and s2 i want to put them in a map like so:
map[s2] = s1;
as you can probably tell the string i use is the result of splitting 1 humongous string on ('}'). the code displayed here is what i do when looping trough this array.

That can only be caused by a attempt to access element on the array that is really undefined. Probably your input is not what you are expecting.
Check if line.length > 1 before you try to read those indexes of the array.
As it seems to be a JSON, may be you should try to parse the JSON, it would make your code more readable and reliable. Check JSON.parse browser compatibility before using it (IE8+).
For example:
var data = JSON.parse('{ "field1": "value1", "field2": "value2" }');
var s1 = data['field1'];
var s2 = data['field2'];
Hope I've helped.

Related

Deserialize JSON string into array of list

I've a string
var my_str="[(0,10),(1,15),(2,48),(3,63),(4,25),(5,95),(6,41),(7,31),(8,5),(15,2)]";
I need to convert it into an array of list. For example,
alert(my_str[1])
would give an output of 1,15.
I've tried the following:
var myarray = JSON.parse(my_str);
but it throws the error "unexpected token ( in JSON at position 1"
I tried this
var myarray = JSON.parse(my_str);
but it throws error "unexpected token ( in JSON at position 1"
So I changed the structure of my string to:
var my_str="[[0,10],[1,15],[2,48],[3,63],[4,25],[5,95],[6,41],[7,31],[8,5],[15,2]]";
That worked like a charm ;)
The problem is that you are using a strange sintax for delimiting inner objects. It would be appropriate to use "[" and "]" instead of "(" and ")".
Anyway you can easily replace them with javascript and make your structure an array of arrays of strings. Sounds a bit creepy, but this way you can create a licit JSON object and benefit of JS native methods.
var my_array = JSON.parse(my_str.replace(/\(/g,'[').replace(/\)/g,']'))
you can now work on my_array object and retrieve couples of numbers using array indexes
my_array[1] ---> 1,15
You have to replace ( by '( and ) by )' ,, then , apply eval :
eval(arr.replace(/(/g,'\'(').replace(/)/g,')\''));
//> ["(0,10)", "(1,15)", "(2,48)", "(3,63)", "(4,25)", "(5,95)", "(6,41)", "(7,31)", "(8,5)", "(15,2)"]
This is a pretty naive idea, but does work (without JSON.parse or eval):
var arr = my_str.replace('[(', '').replace(')]', '').split('),(');
//> ["0,10", "1,15", "2,48", "3,63", "4,25", "5,95", "6,41", "7,31", "8,5", "15,2"]
var arr = my_str.split("),(")
arr[0] = arr[0].slice(2);
arr[arr.length-1] = arr[arr.length-1].slice(0,-2)

Read Value of JSON Result in Jquery

Here is my output of WebMethod through Ajax call:
var item=""[{\"Column1\":\"false\"}]""
There is always one row output,i-e true or false,i want to get the value of Column1,i already try Jquery.ParseJson(item),but it gives Illegal Token o error,Kindly help me how to read this value.Kindly check the inverted commas,this is the exact outcome of my web method, and this outcome and format is a necessary condition of scenario.Thanks.On using loop it gives the error:
If I understand your problem correctly, I think your extra quotes around the strings are a problem, this is invalid syntax.
This works:
var item = "[{\"Column1\":\"false\"}]";
var parsed = JSON.parse(item);
parsed.forEach(function(row) {
console.log(row.Column1);
});
console.log(parsed[0].Column1);
Here is a jsfiddle.
See here about jQuery.ParseJson vs JSON.parse, I prefer JSON.parse, but either should work fine.
In the case of older browsers without forEach use a for loop or a library like underscore.
var item="[{\"Column1\":\"false\"}]";
var parsed = JSON.parse(item);
//if forEach is not supported:
for (var i = 0; i < parsed.length; i++) {
console.log(parsed[i].Column1);
}
console.log(parsed[0].Column1);
Here is a for loop jsfiddle.
I understand that above solutions not work perfectly with your browsers, here is another alternate solution, though I know that it may not fit your scenario, but as your output is either true or false .Instead of using JsonConvert on server end, simply return the object array to client end and read value like this.
var tempo=item[0].Column1;
Not sure about the output of your service but I think you could try this:
str = 'var item=""[{\"Column1\":\"false\"}]""';
str = str.replace(/"/g, '');//remove quotes and slashes to make valid json
eval(str);//evaluate the string
console.log(item[0].Column1);

Javascript Object not working with Native javascript methods like match(), replace etc

Here is the issue:
I go this Code:
var str = {"Acc":10 , "adm_data":"Denied"};
When I do something like:
console.log(str.Acc.match(/[0-9]+/g)) // To Get the Integer Value from the "Acc" key
Firebug Screams:
TypeError: str.Acc.match is not a function
console.log(str.Acc.match(/[0-9]+/g));
See Image:
I always do something like:
var str = "Hello _10";
console.log(str.match(/[0-9]+/g)) // This Works
Why is the Object thingi not working?
PLEASE NOTE:
As mentioned by #Fabrício Matté. The issue was that I was trying to
pass an integer Value to the .match method which does not belong
to integers. The solution was to do what #kundan Karn Suggested. Something like:
str.Acc.toString().match(/[0-9]+/g)// Converting it first to string then match. It worked!
match function works with string. So convert it to string first
str.Acc.toString().match(/[0-9]+/g)
It works just fine: http://jsfiddle.net/nKHLy/
but in order to get rid of the error you might want to try:
var str = {"Acc":"Hello_10" , "adm_data":"Denied"};
console.log(String(str.Acc).match(/[0-9]+/g));
or
var str = {"Acc":"Hello_10" , "adm_data":"Denied"};
console.log(str.Acc.toString().match(/[0-9]+/g));
To know the difference between the 2 options, check: What's the difference between String(value) vs value.toString()

How to properly decode a JSON string encoded using Html.Raw(Json.Encode(Model))?

I am encoding some model data into a html element like this:
#Html.Raw(Json.Encode(Model));
The json string returned looks like this:
{"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo":8314,"TSeqNoSpecified":true,"TestDescr":"HBsAg"},{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6124","SeqNo":9295,"SeqNoSpecified":true,"TSeqNo":8315,"TSeqNoSpecified":true,"TestDescr":"HCV Ab"},{"FrequencyType":"1X","GCDs":"585.3","Identifier":"6","SeqNo":9729,"SeqNoSpecified":true,"TSeqNo":8309,"TSeqNoSpecified":true,"TestDescr":"HD Monthly LS"}],"Frequency":[{"Key":"ANNUAL","Value":"Annually"},{"Key":"BIMONTH","Value":"Bi-Monthly"},{"Key":"BIWEEK","Value":"Bi-Weekly"},{"Key":"MON","Value":"Monthly"},{"Key":"1X","Value":"One Time"},{"Key":"QTR","Value":"Quarterly"},{"Key":"SMAN","Value":"Semi-Annual"},{"Key":"WEEK","Value":"Weekly"}]};
When I try to parse this using JSON.parse, I get an error:
arrayTestList = [];
var jsonTestList = $('#TestList').text();
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); // <===== this line is failing
Unable to get value of the property '0': object is null or undefined
How do I convert this jsonTestList string into a javascript array so that I can access elements of arrayTestList properly?
Edit:
Sorry, I forgot to mention my edit. Basically above javascript code is inside a Partial View 2. The code where I am json encoding the model is in another Partial View 1. From P V 2, I cannot access the model object of P V 1, so I am just dumping the contents into a div tag, so that I can access this list TestList element.
Try removing this line:
jsonTestList = JSON.stringify(jsonTestList);
jsonTestList is already a JSON string
The issue is now resolved.
I was getting an invalid character, but couldn't immediately recognize which character it was that was causing the problem. I found that my JSON string isn't valid because of the trailing semicolon that was output by the Json.Encode method. I validated the JSON string # http://jsonlint.com.
Once I removed that semicolon, the json string is populated as a JavaScript array into arrayTestList object.
Now just this works, as mentioned in both the answers above, JSON.stringify is not needed.
var arrayTestList = [];
var jsonTestList = $('#TestList').text().replace(";","");
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]);
Why are you using Json.Encode? Also in your code, why are you writing redundant code first you are using JSON.stringify and the JSON.parse same object.
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
As per my understanding just Html.Raw will work
In JavaScript
var jsonObject = #Html.Raw(Model.TestList); //Here you will get JavaScript Object
var jsonTestList = jsonObject.TestList;

Object has no method 'replace'

I'm try to run this function, which grabs all the checked checkbox values in to a comma separated string, and converts "," in to ", ", so it reads better. The problem is I'm getting a strange error:
$('.name_boxes').live('click', function() {
var all_boxes = $('.name_boxes');
var all_boxes_values = []
for (var i = 0; i < all_boxes.length; i++) {
if (all_boxes[i].checked) {
all_boxes_values.push(all_boxes[i].value)
}
}
var all_boxes_values_clean = all_boxes_values.replace(/,/g,", ");
alert(all_boxes_values_clean);
});
The console error says:
Uncaught TypeError: Object Aaron Ramsey,Aaron Renfree has no method 'replace'.
I'm not getting the alert box.
This is a bit beyond me, can anybody explain what I'm doing wrong?
Although alert(some_array) prints a string representation of the array, the array itself is not a string. Thus, it does not have .replace. alert is forced to convert it into a string because the alert box can only show characters.
You can simply join using a custom separator, though. join is a function of arrays:
var all_boxes_values_clean = all_boxes_values.join(", ");
As a side note, I recommend console.log over alert because it:
shows the actual object/array instead of a string representation (especially useful with objects instead of the useless [object Object] you receive with alert)
frees you from closing the popup each time
keeps track of other logs so that you have an actual log of logs
all_boxes_values is an array, not a strings and thus it has no replace method.
Try
var all_boxes_values_clean = all_boxes_values.join(", ");
If you insist on performing regular expressions, convert an array to string first: all_boxes_values.toString().

Categories