2

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 values not keys. Wondered if anybody else hade written a regexp or parser to replace the text making up the key?

1
  • Are you dealing with JSON, or an actual JavaScript object? They are different things. Commented Dec 13, 2010 at 20:59

1 Answer 1

11

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.