我有一个像这样的JS字符串(来自AJAX)
{"Task":"Hours per Day","Slep":22,"Work":25,"Watch TV":15,"Commute":4,"Eat":7,"Bathroom":17}
我想将其转换为这种格式 -
[["Task", "Hours per Day"], ["Work", 11], ["Eat", 2], ["Commute", 2], ["Watch TV", 2], ["Sleep", 7]]
借助JS和jQuery。
有什么办法吗?
答案 0 :(得分:3)
你可以这样做:
// Parse your string into an object
var obj = JSON.parse(json);
var array = [];
// Iterate on your object keys
for (var key in obj) {
array.push([key, obj[key]]);
}
// Convert array into a JSON
json = JSON.stringify(array);
如果您想支持旧版浏览器,for (var key in obj)
可能无效。如果您愿意,也可以这样做:
// Parse your string into an object
var obj = JSON.parse(json);
var array = [],
keys = Object.keys(obj);
// Iterate on your object keys
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
array.push([key, obj[key]]);
}
// Convert array into a JSON
json = JSON.stringify(array);