问题描述:

I'm working on some website, and am using JSON. My problem is the JSON.parse method, I use it to send a simple array, and append to an array the values. And I always get an extra element at the end that us just commas. here is the 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);

First in IE its not working at all (exception is thrown).

Second chrome the result is that clientList is an array of 5 strings, while the last one is ',,, '.

Why is that extra value there? Can I get rid of it (without just popping the array at the end)? And what is wrong with IE?

网友答案:

This will work:

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

IE doesn't have JSON as a default in the browser. You need a library like json2.

As for your question, that callback function is really in order to transform your object not build 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

网友答案:

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

clientList = $.parseJSON(responseText);

should do the job under any browser (although I did not test it under IE).

相关阅读:
Top