Jump to content

Full Stringification Of Javascript Objects.


madsovenielsen

Recommended Posts

Hello I have these JavaScript functions from http://jsconsole.com/ They are supposed to stringify a object and display it as JSON.

<html><head>	<title></title>	<script type="text/javascript">		function sortci(a,  {			return a.toLowerCase() < b.toLowerCase() ? -1 : 1;		}		function stringify(o, simple, visited) {			var json = '', i, vi, type = '', parts = [], names = [], circular = false;			visited = visited || [];			try {				type = ({}).toString.call(o);			}			catch (e) { // only happens when typeof is protected (...randomly)				type = '[object Object]';			}			// check for circular references			for (vi = 0; vi < visited.length; vi++) {				if (o === visited[vi]) {					circular = true;					break;				}			}			if (circular) {				json = '[circular]';			} else if (type == '[object String]') {				json = '"' + o.replace(/"/g, '\\"') + '"';			} else if (type == '[object Array]') {				visited.push(o);				json = '[';				for (i = 0; i < o.length; i++) {					parts.push(stringify(o[i], simple, visited));				}				json += parts.join(', ') + ']';				json;			} else if (type == '[object Object]') {				visited.push(o);				json = '{';				for (i in o) {					names.push(i);				}				names.sort(sortci);				for (i = 0; i < names.length; i++) {					parts.push(stringify(names[i], undefined, visited) + ': ' + stringify(o[names[i]], simple, visited));				}				json += parts.join(', ') + '}';			} else if (type == '[object Number]') {				json = o + '';			} else if (type == '[object Boolean]') {				json = o ? 'true' : 'false';			} else if (type == '[object Function]') {				json = o.toString();			} else if (o === null) {				json = 'null';			} else if (o === undefined) {				json = 'undefined';			} else if (simple == undefined) {				visited.push(o);				json = type + '{';				for (i in o) {					names.push(i);				}				names.sort(sortci);				for (i = 0; i < names.length; i++) {					try {						parts.push(names[i] + ': ' + stringify(o[names[i]], true, visited)); // safety from max stack					} catch (e) {						if (e.name == 'NS_ERROR_NOT_IMPLEMENTED') {							// do nothing - not sure it's useful to show this error when the variable is protected							// parts.push(names[i] + ': NS_ERROR_NOT_IMPLEMENTED');						}					}				}				json += parts.join(',\n') + '\n}';			} else {				try {					json = o + ''; // should look like an object					} catch (e) { }			}			return json;		}	</script>	<script type="text/javascript">		function dispSerial() {			document.write("<pre>" + stringify(navigator) + "</pre>");		}	</script></head><body onload="dispSerial()"></body></html>

I get different output in IE9 and Firefox, i know that some of the methods don't contain the same information across different browsers, but the output is radically different. IE9

{"appCodeName": "Mozilla","appMinorVersion": "0","appName": "Microsoft Internet Explorer","appVersion": "5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)","cookieEnabled": true,"cpuClass": "x86","mimeTypes": {},"msDoNotTrack": "0","onLine": true,"opsProfile": {},"platform": "Win32","plugins": {"length": 0},"systemLanguage": "da","userAgent": "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)", "userLanguage": "da","userProfile": [circular]}

Firefox 7.0.1

[object Navigator]{appCodeName: "Mozilla",appName: "Netscape",appVersion: "5.0 (Windows)",buildID: "20110928134238",cookieEnabled: true,geolocation: [object GeoGeolocation],javaEnabled: function javaEnabled() {	[native code]},language: "en-US",mimeTypes: [object MimeTypeArray],mozIsLocallyAvailable: function mozIsLocallyAvailable() {	[native code]},onLine: true,oscpu: "Windows NT 6.1",platform: "Win32",plugins: [object PluginArray],product: "Gecko",productSub: "20100101",registerContentHandler: function registerContentHandler() {	[native code]},registerProtocolHandler: function registerProtocolHandler() {	[native code]},taintEnabled: function taintEnabled() {	[native code]},userAgent: "Mozilla/5.0 (Windows NT 6.1; rv:7.0.1) Gecko/20100101 Firefox/7.0.1",vendor: "",vendorSub: ""}

The output in Firefox is correct, but the output in IE9 is missing some of the methods, e.g. geolocation etc. The strange thing is that the stringify function works on http://jsconsole.com/ in IE9 type "navigator" in the console and see for yourself. Any suggestions ?

Link to comment
Share on other sites

The output from IE is valid JSON, the output from Firefox is not. That function isn't set up to handle objects of type "[object Navigator]", it checks for several other types but not that one. IE probably reports it as a generic object. You can see that there are several other objects that are not caught where it just displays the type of object, and it's also trying to display several functions without checking if they're functions first. I would suggest that you use a different library, that one looks like it was made for IE.

Link to comment
Share on other sites

The output from IE is valid JSON, the output from Firefox is not. That function isn't set up to handle objects of type "[object Navigator]", it checks for several other types but not that one. IE probably reports it as a generic object. You can see that there are several other objects that are not caught where it just displays the type of object, and it's also trying to display several functions without checking if they're functions first. I would suggest that you use a different library, that one looks like it was made for IE.
Go to jsconsole.com and type navigator, both in IE and Firefox, the function produce equal output. But when i use the function Its the Firefox output that is correct. Also, try to press F12 in IE9, then under script, type "navigator" and evaluate that, then add the output to the watch list. the function should produce the same output, like in Firefox.
Link to comment
Share on other sites

I don't know what you're asking. If you're looking for a function to use to convert an object to JSON format, this is not the function you're looking for. Even though it uses a variable called "json", the output is not valid JSON. It is a debugging function for printing the properties and methods of an object, similar to print_r in PHP. If your question is something other than that then let me know.

Link to comment
Share on other sites

I don't know what you're asking. If you're looking for a function to use to convert an object to JSON format, this is not the function you're looking for. Even though it uses a variable called "json", the output is not valid JSON. It is a debugging function for printing the properties and methods of an object, similar to print_r in PHP. If your question is something other than that then let me know.
I dont want JSON, i just want a representation of the the object i put into the function. The firefox output above is perfect, i just dont understand why the output is not simila in FF and IE. it is on jsconsole.com, but when i use the function i get different outputs. The output in IE should be equal to this:
[object Navigator]{appCodeName: "Mozilla",appMinorVersion: "0",appName: "Microsoft Internet Explorer",appVersion: "5.0 (compatible; MSIE 9.0; Windows NT 6.0; WOW64; Trident/5.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.30729; .NET CLR 3.5.30729; .NET4.0C)",browserLanguage: "en-us",cookieEnabled: true,cpuClass: "x86",geolocation: [object Geolocation],javaEnabled:function javaEnabled() {[native code]},mimeTypes: [object MSMimeTypesCollection],msDoNotTrack: "0",onLine: true,platform: "Win32",plugins: [object MSPluginsCollection],systemLanguage: "da",taintEnabled:function taintEnabled() {[native code]},userAgent: "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; WOW64; Trident/5.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.30729; .NET CLR 3.5.30729; .NET4.0C)",userLanguage: "da"} 

The output from the function should be exactly like the above, its taken from jsconsole.com

Link to comment
Share on other sites

I don't have IE9 here and that site doesn't work with IE8, but you may want to use the developer tools to inspect the navigator object and see if it's what you think it is. That site may be modifying it.
I am using the developer tool in IE9 (F12), this is what i get from navigator:
[object navigator]appCodeName: "Mozilla"appMinorVersion: "0"appName: "Microsoft Internet Explorer"browserLanguage: "en-us"cookieEnabled: truecpuClass: "x86"getlocation: [object Geolocation]javaEnabled:function javaEnabled() {[native code]}mimeTypes: [object MSMimeTypesCollection]msDoNotTrack: "0"onLine: trueplatform: "Win32"plugins: [object MSPluginsCollection]systemLanguage: "da"taintEnabled:function taintEnabled() {[native code]}userAgent: "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"userLanguage: "da"

Thats pretty far from the output i get when i am using the function, but its exactly what i get on jsconsole.com

Link to comment
Share on other sites

Found the problem now. My test site test.htm was making the browser operate in quirks mode, and the navigator object don't contain the same information in that mode.With quirks mode enabled:

{   "appCodeName": "Mozilla",   "appMinorVersion": "0",   "appName": "Microsoft Internet Explorer",   "appVersion": "5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",   "cookieEnabled": true,   "cpuClass": "x86",   "mimeTypes": {},   "msDoNotTrack": "0",   "onLine": true,   "opsProfile": {},   "platform": "Win32",   "plugins": {"length": 0},   "systemLanguage": "da",   "userAgent": "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",   "userLanguage": "da",   "userProfile": [circular]} 

IE9 Standards

[object Navigator]{appCodeName: "Mozilla",appMinorVersion: "0",appName: "Microsoft Internet Explorer",appVersion: "5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",browserLanguage: "en-us",cookieEnabled: true,cpuClass: "x86",geolocation: [object Geolocation],javaEnabled: function javaEnabled() {    [native code]},mimeTypes: [object MSMimeTypesCollection],msDoNotTrack: "0",onLine: true,platform: "Win32",plugins: [object MSPluginsCollection],systemLanguage: "da",taintEnabled: function taintEnabled() {    [native code]},userAgent: "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",userLanguage: "da"}

If somebody know why the object don't contain the same data and methods, please explain.

Link to comment
Share on other sites

Quite a few things change in IE when it's in quirks mode, including enabling bugs and side effects that some people relied on. The point is to make old or badly-written scripts that used to target older versions work in the newer versions also.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...