如何将此实例变量转换为 JavaScript 对象数组
我知道有些事我必须做
但是当我尝试的时候。它完全出错了..
这就是我得到的:(带有引号)
@updates = [
"{'24548_0_load_results': ['1630609','2015-04-07 13:51:03 UTC','7 minutes']}",
"{'24548_0_load_results': ['1630610','2015-04-07 13:51:03 UTC','7 minutes']}"
]
用这个创建了上面的内容:
@updates = []
records.each do |r|
updates << "{ '" + t.search_table_id.to_s + "': " + Search.load_post_result(r, s).to_s + " }"
end
这就是我需要的:
var obj1 = {
"loads": [
{'24547_1428357240_load_results' : ['1630607','2015-04-06 18:35:46 UTC','8 minutes']},
{'24547_1428357240_load_results' : ['1630606','2015-04-06 18:35:47 UTC','8 minutes']}
]
};
这是我尝试运行这个对象数组的脚本:
$.each(obj1["loads"], function(k, v){
$.each(v, function(key, value) {
alert(key + ": " + value);
})
});
编辑: 这就是我现在拥有的
var obj1 = {
"loads": []
};
for (string in <%= @updates1 %>){
obj1["loads"].push(JSON.parse(string.replace(/'/g,'\"')));
}
$.each(obj1["loads"], function(k, v){
$.each(v, function(key, value) {
alert(key + ": " + value);
})
});
响应中看起来像这样:
var obj1 = {
"loads": []
};
for (string in ["{ '24549_1428420484_load_results': ['1630610','2015-04-07 14:44:37 UTC','44 minutes','Springfield, MO','Dallas, TX','04/07','04/07','Full','Flatbed or Van or Reefer','','53','0.00'] }", "{ '24549_1428420484_load_results': ['1630609','2015-04-07 13:51:03 UTC','about 2 hours','Springfield, MO','Dallas, TX','04/10','04/11','Full','Flatbed or Van or Reefer','','53','0.00'] }"]){
obj1["loads"].push(JSON.parse(string.replace(/'/g,'\"')));
}
$.each(obj1["loads"], function(k, v){
$.each(v, function(key, value) {
alert(key + ": " + value);
})
})
;
最佳答案
你可以用 JavaScript 来实现,如下所示:
JSON.parse("YourString".replace(/'/g,'\"'))
这是一个要演示的 fiddle 。
https://jsfiddle.net/ab19ha1o/
您需要替换单引号才能正确解析 JSON,因此这是一种快速但肮脏的方法:)
编辑:这是 JSON 解析的 SO 线程:jQuery.parseJSON single quote vs double quote
您只需要迭代每个字符串即可获取对象。
编辑:完整的传输看起来像这样:
for (string in updates){
obj1["loads"].push(JSON.parse(string.replace(/'/g,'\"')));
}
关于javascript - 将实例变量转换为 JavaScript 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29494034/