JavaScript log object as JSON | Example code

  • by

If you data has perfect JavaScript Object Notation. It makes a pretty good format for objects. Just use console.log(obj) to log object as JSON in JavaScript.

Most debugger consoles support displaying objects directly. Depending on your debugger this most likely will display the object in the console as a collapsed tree. You can open the tree and inspect the object.

Example log object as JSON in JavaScritp

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
   let obj = {
    "employees":[
    {"fn":"John", "ln":"Doe"},
    {"fn":"Anna", "ln":"Smith"},
    {"fn":"Peter", "ln":"Jones"}
    ]
  }

  console.log(obj)
</script>

</body>
</html>

Output:

JavaScript log object as JSON

JSON.stringify(obj) will give you back a string representation of the object.

  <script>
   let obj = {
    "employees":[
    {"fn":"John", "ln":"Doe"},
    {"fn":"Anna", "ln":"Smith"},
    {"fn":"Peter", "ln":"Jones"}
    ]
  }

  console.log(JSON.stringify(obj))
</script>

Output:

{“employees”:[{“fn”:”John”,”ln”:”Doe”},{“fn”:”Anna”,”ln”:”Smith”},{“fn”:”Peter”,”ln”:”Jones”}]}

Read more: Console log object in JavaScript | Multiple ways

Do comment if you have any doubts or suggestions no this JS log topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.