views:

1359

answers:

6

I need to be able to take any JSON data and print the key/value pairs.

(something similar to print_r() in PHP)

Is this even possible with javascript?

+1  A: 

can you simply use the following:

 document.write('<h2>Your Text and or HTML here.</h2>');
Jay
+1  A: 

I would recommend you to get a JSON parsing library like JSON2 for being able to "stringify" your objects, then you can simply:

var myString = JSON.stringify(myObject);

myString will now contain a string representation of myObject.

But if it's for debugging purposes I would recommend you to get a JavaScript debugger, like Firebug, you get a lot of useful functions in the Console API.

CMS
A: 

Yes, you can process a surprising amount of info through alert, and you can also use it for debugging.

Here is a print_r equivalent for javascript also.

function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}

good luck with your project!

Jeremy Morgan
argh i just had about half of that written.
Shawn Simon
+1  A: 

I usually just quickly create a log function that allows you change the logging method. Write enablers/disablers or comment out to choose the options.

function log(msg){
  console.log(msg); //for firebug
  document.write(msg); //write to screen
  $("#logBox").append(msg); //log to container
}

Update: Info on Firebug's Console API

Glennular
A: 

FireBug is a great tool! Indispensable! I found it eliminates the need to write debug data into my pages and I can view JSON all day long.

Upper Stage
A: 

I need to be able to take any JSON data and print the key/value pairs.

Well then print the JSON data. JSON is a notation, not an object. If you have JSON data, you already have all you need. If you want it to be a little more fancy, you might want to add a linebreak after every "\s*,.

If you want to deconstruct an object, it's not possible unless you're using JavaScript, as ECMAScript can't create cyclic references in a single object literal. If this is JavaScript-only, then you can use uneval(object), which will make use of sharp variables. (eg. ({x:#1={y:#1#}})).

Eli Grey