0

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

3
  • 2
    create your JSON so that the key is only bar. Commented Oct 22, 2013 at 16:33
  • What does "just def" mean? Who creates the json - do you? If it's you, just follow @JustinWood advice and modify how you output it. Commented Oct 22, 2013 at 16:35
  • The json is converted from xml with namespace like that, I can't change it :( Commented Oct 22, 2013 at 16:40

2 Answers 2

2

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

1 Comment

what if the structure of the json is more complex, eg: it has child and array in it?
0

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.

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.