Why am I getting an extra element at the end of the JSON?

I am working on some website and use JSON. My problem is the JSON.parse method, I use it to send a simple array and add values ​​to the array. And I always get an extra element at the end that we are just commas. here is a simplified code:

responseText = '["dummy1", "dummy2", "dummy3", "dummy4"]'; var clientList=[]; try { JSON.parse(responseText, function(key, val){clientList.push(val)}); } catch (e) { alert('no'); } alert(clientList.length); 

At first in IE it doesn’t work at all (exception thrown).

As a result of the second chrome, the result of clientList is an array of 5 lines, and the last is ",,".

Why does this added value exist? Can I get rid of it (just without popping the array at the end)? And what is wrong with IE?

+2
source share
2 answers

This will work:

 responseText = '["dummy1", "dummy2", "dummy3", "dummy4"]'; var clientList=[]; try { clientList = JSON.parse(responseText); } catch (e) { alert('no'); } 

IE does not have default JSON in the browser. You need json2 library.

As for your question, this callback function is really intended to transform your object, not create it. For example:

 var transformed = JSON.parse('{"p": 5}', function(k, v) { if (k === "") return v; return v * 2; }); // transformed is { p: 10 } 

From parse

+4
source

There are differences in using JSON across browsers. One way is to do what IAbstractDownvoteFactory said. Another way is to use jQuery library and

 clientList = $.parseJSON(responseText); 

should do the job in any browser (although I have not tested it in IE).

0
source

All Articles