开发者

Replace keys JSON in javascript

Let's say I have a JSON object like

var myjson = {
   "com.mycompany.top.Element" : {
      "com.mycompany.top.count" : 10,
      "com.mycompany.top.size" : 0
      ....
   }
};

And I want to replace the dots/periods in the keys with a colon so the JSON becomes:

var myjson = {
   "com:mycompany:top:Element" : {
      "com:mycompany:top:count" : 10,
      "com:mycompany:top:size" : 0
      ....
   }
};

The JSON2 from Doublos Crockford just replaces the valu开发者_开发百科es not keys. Wondered if anybody else hade written a regexp or parser to replace the text making up the key?


You can use this recursive function:

function rewriteProperties(obj) {
    if (typeof obj !== "object") return obj;
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            obj[prop.replace(/\./g, ":")] = rewriteProperties(obj[prop]);
            if (prop.indexOf(".") > -1) {
                delete obj[prop];
            }
        }
    }
    return obj;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜