Is there a quick function to convert JSON objects received via jQuery getJSON to a string variable dump (for tracing/debugging purposes)?
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);
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/
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
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>"' + data[key] + '"</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>
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;
}
Related
I need a function that can serialize object of type {"a":"val", "b":{}, "c":[{}]} without JSON.stringify (cause the environment simply does not has JSON object) or using jquery and any other library. The code bellow is what I have at this moment:
function objToString(obj) {
if (obj == null) return null;
var index = 0;
var str = '{';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += index != 0 ? "," : "";
str += '"' + p + '":' + (typeof (obj[p]) == 'object' ? objToString(obj[p]) : itemToJsonItem(obj[p]));
index++;
}
}
str += "}";
return str;
}
function itemToJsonItem(item) {
return isNaN(item) ? '"' + item + '"' : item;
}
This function can deal with objects, nested objects but not with arrays. Node "c" from mentioned object will looks like "c":{"0":{...}} and not like array. Unsurprising "c".constructor === Array is false cause it interpreted as function and not as array. This is complete code where you can see what happens.
<div id="div_result"></div>
<script>
var test = { "a": "val", "b": [{"c":"val c"}]};
function objToString(obj) {
if (obj == null) return null;
var index = 0;
var str = '{';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += index != 0 ? "," : "";
str += '"' + p + '":' + (typeof (obj[p]) == 'object' ? objToString(obj[p]) : itemToJsonItem(obj[p]));
index++;
}
}
str += "}";
return str;
}
function itemToJsonItem(item) {
return isNaN(item) ? '"' + item + '"' : item;
}
document.getElementById("div_result").innerHTML = objToString(test);
</script>
I will really appreciate help, at this moment serialized object created by toSerialize function inside of each object but we want to make it with outside standard function.
Try to use JSON 3. It is polyfill library for window.JSON. It exposes JSON.stringify and JSON.parse methods.
the below code is the JSON response i recieve from an API. unfortunately i cannot change the way this response is sent, i can only use this response as is within the scope of Javascript/jQuery.
My goal is to transform this into a HTML table.
I have attempted to do this already myself;
function CreateTableView(objArray, theme, enableHeader) {
// set optional theme parameter
if (theme === undefined) {
theme = 'mediumTable'; //default theme
}
if (enableHeader === undefined) {
enableHeader = true; //default enable headers
}
// If the returned data is an object do nothing, else try to parse
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '<table id="res" class="' + theme + '">';
// table head
if (enableHeader) {
str += '<thead><tr>';
for (var index in array[0]) {
str += '<th scope="col">' + index.toUpperCase() + '</th>';
}
str += '</tr></thead>';
}
// table body
str += '<tbody>';
for (var i = 0; i < array.length; i++) {
str += (i % 2 == 0) ? '<tr class="alt" id="' + array[i]['id'] + '">' : '<tr id="' + array[i]['id'] + '">';
for (var index in array[i]) {
str += '<td style="width:15%;">' + htmlspecialchars_decode(array[i][index]) + '</td>';
}
str += '<td>Edit</td><td>Delete</td></tr>';
}
str += '</tbody>'
str += '</table>';
return str;
}
However I am only able to get the headers to show... But it works well if the JSON response has only one array ie one row returned.
the code above was adapted from several other questions like this on Stackoverflow, I have spent days on this and cannot get these results to show in a table... This is just one example of many other that are returned just like this example and i will need to reuse this solution many times making it very important to me.
"ItemArray":{
"id":"14"
,"0":
{"id":"1","username":"guest","fname":"Guest","lname":"User","email":"example#domain.com","group":"member","active":"0","url":null,"last_activity":null}
,"1":
{"id":"2","username":"system","fname":"Internal","lname":"System","email":"example#domain.com","group":"member","active":"0","url":null,"last_activity":null}
,"2":
{"id":"3","username":"master","fname":"Super","lname":"Admin","email":"example#domain.com","group":"member","active":"0","url":null,"last_activity":null}
,"3":
{"id":"14","username":"apitest","fname":"API","lname":"Test","email":"user#domain.com","group":"member","active":"0","url":null,"last_activity":"2012-10-29 02:48:43"}
}
You can't use array.length for Object, so you need:
for (var o in array) if (array.hasOwnProperty(o)) {
var row = array[o];
}
Ok... The problem is the your item array is parsed into an object. Not an array.
If you log this:
typeof array.length
The result is undefined. So your loops doesn't get run.
I have an object say image
look : {
name : "hello baby",
tag_list : "hello",
collection_id : 1,
category_id : 1
},
I want to serialize this object so that it can be sent via POST / GET request to the server. I cannot use JQUery for this purpose.
look[name]=hello
Try this:
var a = [];
for (var p in obj)
a.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
var qstring = a.join("&");
Code taken from http://www.codeproject.com/Tips/46827/Serialize-Object-in-Javascript
function serialize(obj)
{
var returnVal;
if(obj != undefined){
switch(obj.constructor)
{
case Array:
var vArr="[";
for(var i=0;i<obj.length;i++)
{
if(i>0) vArr += ",";
vArr += serialize(obj[i]);
}
vArr += "]"
return vArr;
case String:
returnVal = escape("'" + obj + "'");
return returnVal;
case Number:
returnVal = isFinite(obj) ? obj.toString() : null;
return returnVal;
case Date:
returnVal = "#" + obj + "#";
return returnVal;
default:
if(typeof obj == "object"){
var vobj=[];
for(attr in obj)
{
if(typeof obj[attr] != "function")
{
vobj.push('"' + attr + '":' + serialize(obj[attr]));
}
}
if(vobj.length >0)
return "{" + vobj.join(",") + "}";
else
return "{}";
}
else
{
return obj.toString();
}
}
}
return null;
}
For plain one dimensional objects, you can use
var ser ="";
for (var o in look) ser += "&"+o+"="+encodeURIComponent(look[o]);
alert(ser.substring(1));
This, adds a stringify method to your objects, and a parseJSON method to your strings.
source: JSON.org
Try using for..in loop. It gets each variable from object.
function serialize(obj)
{
var serialized = "";
for (variable in obj)
{
if(serialized != "") serialized += "&";
serialized += variable + "=" + encodeURIComponent(obj[variable]);
}
}
Simply use:
var look = {
name : "hello baby",
tag_list : "hello",
collection_id : 1,
category_id : 1
};
var serialized_object = JSON.stringify(look); // to serialize an object
var deserialized_object = eval('('+ serialized_object + ')'); // to deserialize an object
Is there some way to render all the literal objects and the literal objects within them using mustache? Being a neophyte at this I wondered if the following would work...
var data2 = {};
data2["collector"]={"sname":"Collector", "lname":"Collector", "V":[11,12,13,14,15]};
data2["storage"] ={"sname":"Storage", "lname":"Storage", "V":[21,22,23,24,25]};
data2["aux1"] ={"sname":"Aux1", "lname":"Loop High", "V":[31,32,33,34,35]};
data2["aux2"] ={"sname":"Aux2", "lname":"Loop Low", "V":[41,42,43,44,45]};
data2["aux3"] ={"sname":"Aux3", "lname":"Aux3", "V":[51,52,53,54,55]};
data2["aux4"] ={"sname":"Aux4", "lname":"Aux4", "V":[61,62,63,64,65]};
var T2 = "<table border='1'>" +
"{{#.}}<tr>" +
"{{#.}}" +
"<td>{{.}}</td>" +
"{{/.}}" +
"</tr>" +
"{{/.}}" +
"</table>"
html = Mustache.to_html(T2, data2);
but of course it doesn't. I get
{{/.}}
Since the goal was to use mustache, here's the final deal using mustache to expand the array.
I don't know if Jesse meant to put embedded literal objects in tables within table or not but that was not my goal. I deleted wrap and all from the function in this version as I either didn't need them or understand why they were there. I remain indebted to Jesse for this hint; I doubt I would have come up with anything so clever.
var getMustache = function(data, depth)
{
var r = "";
if (depth == 0)
{
r=r+"<tr>";
}
for(var d in data)
{
if(data.hasOwnProperty(d))
{
if(typeof data[d] =="object")
{
if (data[d].length) // is it an array?
{
var T = "{{#" + d + "}}<td>{{.}}</td>{{/" + d + "}}";
r += Mustache.to_html(T, data);
}
else
{
r += getMustache(data[d], depth+1);
}
}
else
{
r += "<td>" + data[d] + "</td>";
}
}
if (depth == 0)
{
r=r+"</tr>";
}
}
return r;
}
var T2 = "<table border='1'>" + getMustache(data2,0) + "</table>";
html = Mustache.to_html(T2, data2);
document.write(html);
Seems like you could just make a recursive function for this - mustache is pretty static, but recursion is perfect for looking up all the nodes in a deep object.
Untested hypothetical code:
var data2 = {};
data2["collector"]={"sname":"Collector", "lname":"Collector", "V":[11,12,13,14,15]};
data2["storage"] ={"sname":"Storage", "lname":"Storage", "V":[21,22,23,24,25]};
data2["aux1"] ={"sname":"Aux1", "lname":"Loop High", "V":[31,32,33,34,35]};
data2["aux2"] ={"sname":"Aux2", "lname":"Loop Low", "V":[41,42,43,44,45]};
data2["aux3"] ={"sname":"Aux3", "lname":"Aux3", "V":[51,52,53,54,55]};
data2["aux4"] ={"sname":"Aux4", "lname":"Aux4", "V":[61,62,63,64,65]};
var getMustache = function(data, wrap, all, depth){
var r = "";
var depth = depth || 0;
for(var d in data){
if(data.hasOwnProperty(d)){
r += "<" + wrap[depth] || all + ">";
if(data[d].length){
r += "{{#" + d + "}}";
r += getMustache(data[d], wrap, all, depth ++);
r += "{{/" + d + "}}";
} else {
r += "{{" + data[d] + "}}";
}
r += "</" + wrap[depth] || all + ">";
}
}
return r;
}
var T2 = "<table border='1'>" + getMustache(data2,['tr','td'],'span');
html = Mustache.to_html(T2, data2);
The following works. It doesn't use mustache facilities at all. I plan to change it so that it uses mustache's iteration on the array.
var getMustache = function(data, wrap, all, depth)
{
var r = "";
if (depth == 0)
{
r=r+"<tr>";
}
for(var d in data)
{
if(data.hasOwnProperty(d))
{
if(typeof data[d] =="object")
{
r += getMustache(data[d], wrap, all, depth+1);
}
else
{
r += "<td>" + data[d] + "</td>";
}
}
if (depth == 0)
{
r=r+"</tr>";
}
}
//alert("r=" + r);
return r;
}
What is the best way of converting a multi-dimensional javascript array to JSON?
Most of the popular JavaScript frameworks have JSON utility functions included. For instance, jQuery has a function that directly calls a url and loads the JSON result as an object : http://docs.jquery.com/Getjson
However, you can get an open-source JSON parser and stringifier from the json website :
https://github.com/douglascrockford/JSON-js
Then, simply include the code and use the JSON.stringify() method on your array.
The "best" way has been provided by the other posters. If you don't need the full encoding features of the referenced libraries, and only need to encode simple arrays, then try this:
<!DOCTYPE html>
<html>
<head>
<title>Simple functions for encoding Javascript arrays into JSON</title>
<script type="text/javascript">
window.onload = function() {
var a = [
[0, 1, '2', 3],
['0', '1', 2],
[],
['mf', 'cb']
],
b = [
0, '1', '2', 3, 'woohoo!'
];
alert(array2dToJson(a, 'a', '\n'));
alert(array1dToJson(b, 'b'));
};
function array2dToJson(a, p, nl) {
var i, j, s = '{"' + p + '":[';
nl = nl || '';
for (i = 0; i < a.length; ++i) {
s += nl + array1dToJson(a[i]);
if (i < a.length - 1) {
s += ',';
}
}
s += nl + ']}';
return s;
}
function array1dToJson(a, p) {
var i, s = '[';
for (i = 0; i < a.length; ++i) {
if (typeof a[i] == 'string') {
s += '"' + a[i] + '"';
}
else { // assume number type
s += a[i];
}
if (i < a.length - 1) {
s += ',';
}
}
s += ']';
if (p) {
return '{"' + p + '":' + s + '}';
}
return s;
}
</script>
</head>
<body>
</body>
</html>
Not sure I fully understand your question, but if you are trying to convert the object into a string of JSON then you probably want to look at the native JSON support in all the new browsers. Here's Resig's post on it. For browsers that don't yet support it try the json2.js library. JSON.stringify(obj) will convert your object to a string of JSON.
This will convert all combinations of arrays within objects and vice versa including function names:
function isArray(a){var g=a.constructor.toString();
if(g.match(/function Array()/)){return true;}else{return false;}
}
function objtostring(o){var a,k,f,freg=[],txt; if(typeof o!='object'){return false;}
if(isArray(o)){a={'t1':'[','t2':']','isarray':true}
}else {a={'t1':'{','t2':'}','isarray':false}}; txt=a.t1;
for(k in o){
if(!a.isarray)txt+="'"+k+"':";
if(typeof o[k]=='string'){txt+="'"+o[k]+"',";
}else if(typeof o[k]=='number'||typeof o[k]=='boolean'){txt+=o[k]+",";
}else if(typeof o[k]=='function'){f=o[k].toString();freg=f.match(/^function\s+(\w+)\s*\(/);
if(freg){txt+=freg[1]+",";}else{txt+=f+",";};
}else if(typeof o[k]=='object'){txt+=objtostring(o[k])+",";
}
}return txt.substr(0,txt.length-1)+a.t2;
}
You could use the encode function of this library.
I've modified a bit the code previously provided... because a JSON has this format: [{"object":{"property_1":"value_1","property_2":"value_2"}}]
So, the code would be...
<!DOCTYPE html>
<html>
<head>
<title>Simple functions for encoding Javascript arrays into JSON</title>
<script type="text/javascript">
window.onload = function(){
var a = [['property_1','value_1'],['property_2', 'value_2']];
alert("Comienzo..., paso ////"+a+"\\\\\\ a formato JSON");
var jsonSerialized = array2dToJson(a, 'object');
alert(jsonSerialized);
};
// Estructura de JSON [{"object":{"property_1":"value_1","property_2":"value_2"}}]
function array2dToJson(a, p, nl) {
var i, j, s = '[{"' + p + '":{';
nl = nl || '';
for (i = 0; i < a.length; ++i) {
s += nl + array1dToJson(a[i]);
if (i < a.length - 1) {
s += ',';
}
}
s += nl + '}}]';
return s;
}
function array1dToJson(a, p) {
var i, s = '';
for (i = 0; i < a.length; ++i) {
if (typeof a[i] == 'string') {
s += '"' + a[i] + '"';
}
else { // assume number type
s += a[i];
}
if (i < a.length - 1) {
s += ':';
}
}
s += '';
if (p) {
return '{"' + p + '":' + s + '}';
}
return s;
}
</script>
</head>
<body>
<h1>Convertir un Array a JSON...</h1>
</body>
</html>
var t = {}
for(var i=0;i<3;i++) {
var _main = {};
var _dis = {}
var _check = {};
_main["title"] = 'test';
_main["category"] = 'testing';
_dis[0] = '';
_dis[1] = '';
_dis[2] = '';
_dis[3] = '';
_check[0] = 'checked';
_check[1] = 'checked';
_check[2] = 'checked';
_check[3] = 'checked';
_main['values'] = _check;
_main['disabled'] = _dis;
t[i] = _main;
}
alert(JSON.stringify(t));
Try this
use this code and very simple develop for more two array
function getJSON(arrayID,arrayText) {
var JSON = "[";
//should arrayID length equal arrayText lenght and both against null
if (arrayID != null && arrayText != null && arrayID.length == arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}
and 3 array
function getJSON(arrayID, arrayText, arrayNumber) {
var JSON = "[";
if (arrayID != null && arrayText != null && arrayNumber!=null && Math.min(arrayNumber.length,arrayID.length)==arrayText.length) {
for (var i = 0; i < arrayID.length; i++) {
JSON += "{";
JSON += "text:'" + arrayText[i] + "',";
JSON += "id:'" + arrayID[i] + "',";
JSON += "number:'" + arrayNumber[i] + "'";
JSON += "},";
}
}
JSON += "]"
JSON = Function("return " + JSON + " ;");
return JSON();
}
JavaScript will correctly encode an object:
var a = new Object;
var a = {};
JavaScript will not encode an array:
var a = new Array();
var a = [];