2010-07-26 5 views
74

¿Existe una función rápida para convertir objetos JSON recibidos a través de jQuery getJSON en un volcado de variable de cadena (para fines de seguimiento/depuración)?Volcado de variable JSON a string

+5

Pregunta tonta: ¿por qué se marcó como spam? – ina

+0

por el mismo motivo por el que mis preguntas reciben votos negativos, ¡a veces los usuarios son inexactos con sus clics! –

Respuesta

109

Sí, JSON.stringify, se puede encontrar here, es included en Firefox 3.5.4 y superiores.

Un secuenciador JSON va en la dirección opuesta, convirtiendo estructuras de datos JavaScript en texto JSON. JSON no admite estructuras de datos cíclicos, por lo que debe tener cuidado de no dar estructuras cíclicas al secuenciador JSON.https://web.archive.org/web/20100611210643/http://www.json.org/js.html

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

está incluido en firefox 3.5.4 !!!!! – ina

+1

También está incluido en Chrome, pero tienes un (enorme) 404 en ese enlace json.org –

+0

@Dean, gracias, he actualizado el enlace. – Anders

27

Puede utilizar console.log() en Firebug o Chrome para obtener una buena vista de objetos de aquí, de esta manera:

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

Si lo que desea es vista la cadena, mira el Resource view in Chrome o la Net view in Firebug para ver la respuesta de cadena real del servidor (no es necesario convertirla ... la recibiste de esta manera).

Si usted quiere tomar esa cadena y descomponerlo para una fácil visualización, hay una excelente herramienta aquí: http://json.parser.online.fr/

12

Yo personalmente uso del montón jquery dump plugin para volcar los objetos, su función() poco similar a print_r de php Uso básico:

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" 
    ) 
} 
*/ 

Es muy legible, también recomiendo este sitio http://json.parser.online.fr/ para crear/analizar/leer json, porque tiene bonitos colores

+1

esto es realmente genial, pero requiere instalar otro plugin (y solo para depuración) – ina

+0

sí, lo sé ... pero cuando estoy buscando respuestas, a menudo encuentro algo útil en las respuestas porque mi problema está relacionado con el problema. este plugin podría ser un poco exagerado cuando tienes un problema simple: P – Ties

5

Aquí está el código que uso. Debería poder adaptarlo a sus necesidades.

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> 
+0

Esto me ayudó :)) – coding

2

algo de esto?

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; 
} 
Cuestiones relacionadas