我想将以下字符串转换为数组
var myEfficientFn = debounce(function() {
show();
}, 250);
$(window).on('resize', myEfficientFn);
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
不幸的是,当我[{id: "1", type: "railroadCrossingSign", latitude: "55.647432", longtitude: "12.187673"}, {id: "2", type: "stationSign", latitude: "55.647444", longtitude: "12.187545"}]
时发生错误,可能是因为字符串中的对象......
如何将带对象的JSON字符串转换为带对象的数组?
答案 0 :(得分:5)
JSON
格式要求您的密钥也必须包含在""
。
var string = '[{"id": "1", "type": "railroadCrossingSign", "latitude": "55.647432", "longtitude": "12.187673"}, {"id": "2", "type": "stationSign", "latitude": "55.647444", "longtitude": "12.187545"}]';
var arr = JSON.parse(string);
console.log(arr);
答案 1 :(得分:1)
为了实现你想要的。 您的JSON键值对也必须采用字符串格式。
说,
var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;
最后,当你使用:
if list is empty then
return:
0;
else
return:
(first_element + constant*eploy(rest_of_the_elements, constant)
您会收到以下结果:
John,30
答案 2 :(得分:0)
一些观察结果:
""
。JSON
已经是JSON Object
,则无需再次parse
,否则会引发错误。
var jsonObj = [{
"id": "1",
"type": "railroadCrossingSign",
"latitude": "55.647432",
"longtitude": "12.187673"
}, {
"id": "2",
"type": "stationSign",
"latitude": "55.647444",
"longtitude": "12.187545"
}];
var newObj = JSON.parse(jsonObj);
console.log(newObj); // Error : Uncaught SyntaxError: Unexpected token o in JSON at position 1