Nick Nick - 1 month ago 6
JSON Question

Clean # symbol from Json object in Javascript

I have this json string, turned into a Javascript object which on one of its levels returns something like this

"link": {
"#tail": "\n\n\t\t",
"#text": "http://static2.server.com/file.mp3"
},


I need to get the value of "text" on Javascript but the "#" symbol is making it imposible to access it.

I have tried cleaning the string like this:

var myJSONString = JSON.stringify(response);
var myEscapedJSONString = myJSONString.replace(/[^\u0000-\u007F]+/g, "").replace("#","t");


But it does not clean the "key" part, even after it has been turned into a string using stringify.

Answer

I don't think there is any problem with the # being used as a key. Any valid string can be used as object key. But if you really want to remove using strings you can replace it using regular expression (Assuming the hash char only in the beginning of each key);

const cleanObj = JSON.parse(JSON.stringify(response).replace(/\"#/gm,'"'))
console.log(cleanObj.link.text);

I could not find any problem also accessing and cleaning up through javascript

var cleanObject = { link: {} };

Object.keys(response.link).map(function(key) { 
    cleanObject.link[key.substring(1)] = response.link[key];
})

Fiddle here: https://jsfiddle.net/p5cvvqzu/

Comments