cerebraldecypher cerebraldecypher - 3 months ago 9
JSON Question

Changing | manipulating json elements or appending namespace prefixes to json elements

thank you in advanced.
I need some help manipulating the following:


  • Ultimately, I really need the simplest way to update the parent json element (or any json element) from the code I have. Is there a way to take my var prime output and change startNode into tns:startNode?



Here's my code

var vPrefix = "tns";
var vNamespace = "http://somenamespace.com";
var badgerfish = function(text) {
return {
"$": text
};
};
var prime = {};
prime.startNode = {};

prime.startNode['@xmlns'] = {"tns": vNamespace};

prime.startNode.test1 = badgerfish("testValue1");
prime.startNode.test2 = badgerfish("testValue2");
prime.startNode.test3 = {};
prime.startNode.test3.subtest1 = badgerfish("subtestValue1");
var node = JSON.stringify(prime);
session.output.write(node);


which outputs the following:

{
"startNode": {
"@xmlns": {
"tns": "http:\/\/somenamespace.com"
},
"test1": {
"$": "testValue1"
},
"test2": {
"$": "testValue2"
},
"test3": {
"subtest1": {
"$": "subtestValue1"
}
}
}
}


and all I'm trying to accomplish is the following (difference is only the tns prefix on startNode):

{
"tns:startNode": {
"@xmlns": {
"tns": "http:\/\/somenamespace.com"
},
"test1": {
"$": "testValue1"
},
"test2": {
"$": "testValue2"
},
"test3": {
"subtest1": {
"$": "subtestValue1"
}
}
}
}

Answer

There's always this:

prime = JSON.parse( JSON.stringify(prime).replace(/startNode/g, 'tns:startNode') );

This will give you back a valid JSON object, but you may not even need parse given you want to output a string representation of the JSON. I am not sure if this is more or less performant than traversing the JSON to update the key.