JSON to string variable dump

JavascriptJqueryJsonVariables

Javascript Problem Overview


Is there a quick function to convert JSON objects received via jQuery getJSON to a string variable dump (for tracing/debugging purposes)?

Javascript Solutions


Solution 1 - Javascript

Yes, JSON.stringify, can be found here, it's included in Firefox 3.5.4 and above.

A JSON stringifier goes in the opposite direction, converting JavaScript data structures into JSON text. JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier. https://web.archive.org/web/20100611210643/http://www.json.org/js.html

var myJSONText = JSON.stringify(myObject, replacer);

Solution 2 - Javascript

You can use console.log() in Firebug or Chrome to get a good object view here, like this:

$.getJSON('my.json', function(data) {
  console.log(data);
});

If you just want to view the string, look at the Resource view in Chrome or the Net view in Firebug to see the actual string response from the server (no need to convert it...you received it this way).

If you want to take that string and break it down for easy viewing, there's an excellent tool here: http://json.parser.online.fr/

Solution 3 - Javascript

i personally use the jquery dump plugin alot to dump objects, its a bit similar to php's print_r() function Basic usage:

var obj = {
            hubba: "Some string...",
            bubba: 12.5,
            dubba: ["One", "Two", "Three"]
        }
$("#dump").append($.dump(obj));
/* will return:
Object { 
     hubba: "Some string..."
     bubba: 12.5
     dubba: Array ( 
          0 => "One"
          1 => "Two"
          2 => "Three"
     )
}
*/

Its very human readable, i also recommend this site http://json.parser.online.fr/ for creating/parsing/reading json, because it has nice colors

Solution 4 - Javascript

Here is the code I use. You should be able to adapt it to your needs.

function process_test_json() {
  var jsonDataArr = { "Errors":[],"Success":true,"Data":{"step0":{"collectionNameStr":"dei_ideas_org_Private","url_root":"http:\/\/192.168.1.128:8500\/dei-ideas_org\/","collectionPathStr":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwrootchapter0-2\\verity_collections\\","writeVerityLastFileNameStr":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwroot\\chapter0-2\\VerityLastFileName.txt","doneFlag":false,"state_dbrec":{},"errorMsgStr":"","fileroot":"C:\\ColdFusion8\\wwwroot\\dei-ideas_org\\wwwroot"}}};
  
  var htmlStr= "<h3 class='recurse_title'>[jsonDataArr] struct is</h3> " + recurse( jsonDataArr );
  alert( htmlStr );
  $( document.createElement('div') ).attr( "class", "main_div").html( htmlStr ).appendTo('div#out');
  $("div#outAsHtml").text( $("div#out").html() ); 
}
function recurse( data ) {
  var htmlRetStr = "<ul class='recurseObj' >"; 
  for (var key in data) {
		if (typeof(data[key])== 'object' && data[key] != null) {
			htmlRetStr += "<li class='keyObj' ><strong>" + key + ":</strong><ul class='recurseSubObj' >";
			htmlRetStr += recurse( data[key] );
			htmlRetStr += '</ul  ></li   >';
		} else {
			htmlRetStr += ("<li class='keyStr' ><strong>" + key + ': </strong>&quot;' + data[key] + '&quot;</li  >' );
		}
  };
  htmlRetStr += '</ul >';	 
  return( htmlRetStr );
}

</script>
</head><body>
<button onclick="process_test_json()" >Run process_test_json()</button>
<div id="out"></div>
<div id="outAsHtml"></div>
</body>

Solution 5 - Javascript

something along this?

function dump(x, indent) {
	var indent = indent || '';
	var s = '';
	if (Array.isArray(x)) {
		s += '[';
		for (var i=0; i<x.length; i++) {
			s += dump(x[i], indent)
			if (i < x.length-1) s += ', ';
		}
		s +=']';
	} else if (x === null) {
	  s = 'NULL';
	} else switch(typeof x) {
		case 'undefined':
			s += 'UNDEFINED';
			break;
		case 'object':
			s += "{ ";
			var first = true;
			for (var p in x) {
				if (!first) s += indent + '  ';
				s += p + ': ';
				s += dump(x[p], indent + '  ');
				s += "\n"
				first = false;
			}
			s += '}';
			break;
		case 'boolean':
			s += (x) ? 'TRUE' : 'FALSE';
			break;
		case 'number':
			s += x;
			break;
		case 'string':
			s += '"' + x + '"';
			break;
		case 'function':
			s += '<FUNCTION>';
			break;
		default:
			s += x;
			break;
	}
	return s;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioninaView Question on Stackoverflow
Solution 1 - JavascriptAndersView Answer on Stackoverflow
Solution 2 - JavascriptNick CraverView Answer on Stackoverflow
Solution 3 - JavascriptTiesView Answer on Stackoverflow
Solution 4 - Javascriptuser579338View Answer on Stackoverflow
Solution 5 - JavascripthotzenView Answer on Stackoverflow