另外一种扁平化、反扁平化json结构的方法(尽量使用“[]”)
{a:{b:1}} <==> {a[“b”]:1} 参考上一篇所做:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | JSON.unflatten = function(data) { "use strict"; if (Object(data) !== data || Array.isArray(data)) return data; var regex = /\.?([^.\[\]]+)|\[(\d+)\]|\[([^\d\W]\w*)\]/g, resultholder = {}; for (var p in data) { var cur = resultholder, prop = "", m; while (m = regex.exec(p)) { cur = cur[prop] || (cur[prop] = (m[2] ? [] : {})); prop = m[2] || m[1] || m[3]; prop = prop.replace(/^[\'\"]|[\'\"]$/g,''); } cur[prop] = data[p]; } return resultholder[""]; }; JSON.flatten = function(data) { var result = {}; function recurse (cur, prop) { if (Object(cur) !== cur) { result[prop] = cur; } else if (Array.isArray(cur)) { for(var i=0, l=cur.length; i<l; i++) recurse(cur[i], prop + "[" + i + "]"); if (l == 0) result[prop] = []; } else { var isEmpty = true; for (var p in cur) { isEmpty = false; recurse(cur[p], prop ? prop+'["'+p+'"]' : p); } if (isEmpty) result[prop] = {}; } } recurse(data, ""); return result; } |