JSON.stringify Not Converting Array.object Correctly
I'm having a problem with JSON.stringify I'm trying to pull all the meta tags out of the page and pass them to a firefox worker file to work through them and to return back an obj
Solution 1:
You could use the following:
var metas = document.getElementsByTagName("meta");
var arr = [];
for (var i = 0; i < metas.length; i++) {
var obj = {};
for (var j = 0; j < metas[i].attributes.length; j++) {
var att = metas[i].attributes[j];
obj[att.name] = att.value;
}
arr.push(obj);
}
var jsonMetas = JSON.stringify(arr);
console.log(jsonMetas);
results in:
[
{
"http-equiv": "content-type",
"content": "text/html; charset=UTF-8"
},
{
"content": "width=1024",
"name": "viewport"
},
{
"charset": "UTF-8"
},
{
"content": "Mozilla Hacks – the Web developer blog",
"name": "title"
}
]
Solution 2:
The reason is that document.getElementsByTagName doesn't return JSON, it returns XML. So, you'd need to use something like this to get your desired output:
var jsonMetas = [];
for (i=0 ; i<metas.length ; i++) {
var thisMeta = {};
for (j=0 ; j<metas[i].attributes.length ; j++) {
thisMeta[metas[i].attributes[j].name] = metas[i].attributes[j].value;
}
jsonMetas.push(thisMeta);
}
Output of JSON.stringify(jsonMetas) for this page:
"[{"name":"relativepagescore","content":"0"},{"name":"title","content":"javascript - JSON.stringify not converting array.object correctly - Stack Overflow"}]"
Post a Comment for "JSON.stringify Not Converting Array.object Correctly"