Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getJSON to console.log() to output json structure

Tags:

json

jquery

I have the following code for getting json data:

$.getJSON( "assessments", function( assessments ) {     console.log(assessments);         }); 

I am perfectly getting all the data but the console has output as

[Object, Object, Object, Object, Object, Object, Object, Object, Object] 

I want to output the values in JSON structure like this:

[ {     "id": 1,     "person": {         "personId": "person1",         "firstName": "Pactric"     },     "manager": {         "managerId": "manager1"     },     "state": {         "stateId": 1,         "description": null     },     "comments": null } ] 

How to console.log() for this data to display exactly as above's JSON structure? I am using $.getJSON NOT $.ajax for this application.

like image 786
jeewan Avatar asked Dec 10 '13 17:12

jeewan


People also ask

Can you console log JSON?

The console. log(JSON. stringify(obj)) method can be useful for logging the object to the console as string, as long as the data in the object is JSON-safe.

How do I view a JSON object in console log?

The simplest way is using the Console log() method to log objects as JSON in JavaScript. The console. log() method called with an object or objects as arguments will display the object or objects.

How do I display a JSON object?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

How do I get JSON response?

json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.


2 Answers

try with

console.log(JSON.stringify(assessments)); 
like image 164
Anand Jha Avatar answered Sep 21 '22 11:09

Anand Jha


Stringify the JSON with indentation like so :

$.getJSON( "assessments", function( assessments ) {     console.log(JSON.stringify(assessments, undefined, 2)) }); 

JSON.stringify(value[, replacer [, space]]) where space is the indent. MDN

like image 30
adeneo Avatar answered Sep 22 '22 11:09

adeneo