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?

6 Answers 6

13

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){
  if (window.console && console.log) {
    console.log(msg); //for firebug
  }
  document.write(msg); //write to screen
  $("#logBox").append(msg); //log to container
}

Update: Info on Firebug's Console API

Update: Added check for non firebug browsers.

Sign up to request clarification or add additional context in comments.

Comments

5

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!

1 Comment

argh i just had about half of that written.
2

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.

Comments

1

can you simply use the following:

 document.write('<h2>Your Text and or HTML here.</h2>'); 

Comments

0

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.

Comments

0

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#}})).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.