Duc
Duc

Reputation: 501

Get json value without string prefix

I have a json like this:

var x = {"foo:bar":"xyz"};

I can get xyz by call x["foo:bar"] but is there anyway to get xzy by calling just bar and remove the foo prefix? something like x["bar"]? The json is converted from xml with namespace like that, I can't change it. Thanks

Upvotes: 0

Views: 1307

Answers (2)

MrCode
MrCode

Reputation: 64526

You can iterate over the property names and remove the prefix:

function removePrefix(x){
    var temp = {};
    for(var key in x){
        temp[key.substr(key.indexOf(':')+1)] = x[key];
    }
    return temp;
}

var x = {"foo:bar":"xyz"};

x = removePrefix(x);

console.log( x['bar'] ); // xzy
console.log( x.bar ); // xyz

Upvotes: 2

SidOfc
SidOfc

Reputation: 4584

You would create a JSON string which would look like this:

var x = {"foo":"xyz"};

your current key: "foo:bar" does not have any special meaning in JSON, it's part of the key.

Upvotes: 0

Related Questions