How to print JSON data in console.log? - javascript

I cant access JSON data from javascript. Please help me how to access data from JSON data in javascript.
i have a JSON data like
{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}
i have tried console.log(data) but log print object object
success:function(data){
console.log(data);
}
How to print console.log particular data?
I need to print
quantity-row_122 = 1
price-row_122 = 35.1

console.log(JSON.stringify(data)) will do what you need. I'm assuming that you're using jQuery based on your code.
If you're wanting those two particular values, you can just access those and pass them to log.
console.log(data.input_data['quantity-row_122']);
console.log(data.input_data['price-row_122']);

I used '%j' option in console.log to print JSON objects
console.log("%j", jsonObj);

To output an object to the console, you have to stringify the object first:
success:function(data){
console.log(JSON.stringify(data));
}

{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}
console.dir() will do what you need. It will give you a hierarchical structure of the data.
success:function(data){
console.dir(data);
}
like so
> Object
> input_data: Object
price-row_122: " 35.1 "
quantity-row_122: "1"
success: true
I don't think you need console.log(JSON.stringify(data)).
To get the data you can do this without stringify:
console.log(data.success); // true
console.log(data.input_data['quantity-row_122']) // "1"
console.log(data.input_data['price-row_122']) // " 35.1 "
Note
The value from input_data Object will be typeof "1": String, but you can convert to number(Int or Float) using ParseInt or ParseFloat, like so:
typeof parseFloat(data.input_data['price-row_122'], 10) // "number"
parseFloat(data.input_data['price-row_122'], 10) // 35.1

I usually do like this:
console.log(JSON.stringify(data, undefined, 4));

If you just want to print object then
console.log(JSON.stringify(data)); //this will convert json to string;
If you want to access value of field in object then use
console.log(data.input_data);

You can also use util library:
const util = require("util")
> myObject = {1:2, 3:{5:{6:{7:8}}}}
{ '1': 2, '3': { '5': { '6': [Object] } } }
> util.inspect(myObject, {showHidden: true, depth: null})
"{\n '1': 2,\n '3': { '5': { '6': { '7': 8 } } }\n}"
> JSON.stringify(myObject)
'{"1":2,"3":{"5":{"6":{"7":8}}}}'
original source : https://stackoverflow.com/a/10729284/8556340

This is an old post but I'm chiming in because (as Narem briefly mentioned) a few of the printf-like features are available with the console.log formatters. In the case of the question, you can benefit from the string, number or json formatters for your data.
Examples:
console.log("Quantity %s, Price: %d", data.quantity-row_122, data.price-row_122);
console.log("Quantity and Price Data %j", data);

Object
input_data: Object
price-row_122: " 35.1 "
quantity-row_122: "1"
success: true

Related

Return JSON from ajax call into HTML div

I've got my javascript ajax call returning json and I'm trying to put it on the HTML page.
I use this code:
success: function(response) {
console.log(response);
for (var i=0;i<response.length;++i)
{
$('#main').append('<div class="name">'+response[i].name+'</>');
}
},
error: function(response) {
alert(response);
}
});
However it seems to print json to my console just fine but I dont get anything returned to the website.
I have a div to collect it in:
<div id="main">Test</div>
Any idea where I am going wrong?
EDIT: The console log response is this:
{totalPages: 0, firstPage: true, lastPage: true, numberOfElements: 0, number: 0, …}
columns: {columnIds: Array(3)}
firstPage: true
lastPage: true
number: 0
numberOfElements: 0
oberonRequestXML: [null]
oberonResponseXML: [null]
summaryData: {totals: Array(3)}
totalElements: 0
totalPages: 0
__proto__: Object
As explained in comments, your JSON response is not an array -- there is no length property, so your loop does not loop. Moreover, you seem to expect an array with objects that have a name attribute. This is nowhere to be seen in the response you get.
Assuming you are calling the right JSON service, the only information you can iterate over is stored in two attributes: columns.columnIds and summaryData.totals. So you would get something, if you code it like this:
console.log(response);
for (var i=0;i<response.columns.columnIds.length;++i) {
$('#main').append('<div class="name">'
+ response.columns.columnIds[i]
+ ': '
+ response.summaryData.totals[i] + '</div>');
}
This assumes that these values are primitive values, which is not clear from the response you got.
But again, this will not output name property values, as they do not appear in your JSON as far as is visible in your question.

Can't access JSON Object no matter what i'm trying

So i have this JSON Structure, which i want to access:
data { payload: "{"state":{"reported":{"measuredata":{…
JSON.parse doesnt work, neither does JSON.stringify.
i only can access payload, if i go any further, i receive error or undefined:
data.payload // works
data.payload["state"] //undefined
data.payload.state // undefined
data.payload[0].state // undefined
data.payload[0]["state"] // undefined
what am i doing wrong?
the thing that i can see is that you have a bad format on your json data { payload: "{"state":{"reported":{"measuredata":{…
it hspuld be witouth the double quote that be after the word payload payload: "{"state"
you have to have something like this
payload: {"state"
You just need to use JSON.parse for payload json string value.
JSON.parse(data.payload).state;
Sample code for parsing.
var data = {
"logged_in":true,
"town":"Dublin",
"state":"Ohio",
"country":"USA",
"products":
{
"pic_id":"1500",
"description":"Picture of a computer",
"localion":"img.cloudimages.us/2012/06/02/computer.jpg",
"type":"jpg",
"childrenimages":
{
"pic_id":"15011",
"description":"Picture of a cpu",
"localion":"img.cloudimages.us/2012/06/02/mycpu.png",
"type":"png"
}
}
};
var data1 = JSON.stringify(data);
var data_final = JSON.parse(data1);
console.log(data_final.products.pic_id);

console.log -> Document { ... }

When I apply "console.log" on an JS Object, the console output this thing :
I20170421-14:54:09.786(2)? Document {
I20170421-14:54:09.787(2)? _id: 'KQ7mdidtcxsQsqNjr',
I20170421-14:54:09.787(2)? name: 'eos test',
I20170421-14:54:09.787(2)? number: 69526,
I20170421-14:54:09.788(2)? part: 'bus',
I20170421-14:54:09.788(2)? active: true,
I20170421-14:54:09.789(2)? cron: 6,
What is this 'Document' ??? How I can remove to comapre this Object with the same without 'Document'...
I'm lost !
This document is an output of 'findOne'. I use Meteor with some packages (mongo#1.1.16, aldeed:simple-schema, aldeed:collection2, mdg:validated-method, mdg:validation-error, dburles:collection-helpers).
Thanks :)
You could compare manually (obj2.field1 === obj2.field1) or just use JSON.stringify in both objects and compare the resulting string.
But in your case I think you are not retrieving the object from mongo as you should.
Use fetch() after the query: DocumentCollection.find({}).fetch() or just .findOne() instead.
Also, if you want to compare 2 Meteor documents, you can use:
_.isEqual(doc1, doc2) (underscore)

AngularJS, $http and transformResponse

I'm getting a strange behaviour with AngularJS's $http and not really understanding how transformResponse works (the docs are a bit light on this one).
WebAssets.get = function () {
return $http.get('/api/webassets/list', {
transformResponse: [function (data, headersGetter) {
// not sure what to do here?!
return data;
}].concat($http.defaults.transformResponse) // presume this isn't needed, added for clarity
}).then(function (response) {
return new WebAssets(response.data);
});
};
The api returns an array of objects:
[{"webasset_name": "...", "application_id": "...", "etc": "..."}, ... ]
But when transformResponse has done it's evil business the data has transformed into an indexed object:
{"0":{"webasset_name":"...","application_id":"...", "etc": "..."}, "1":....}
I want to keep the original data structure (an array of objects).
To get angular to not convert your data into an object you need to override the behavior of the default $httpProvider.defaults.transformResponse. It is actually an array of transformers.
You could just set it to be empty: $http.defaults.transformResponse = [];
Here is an example transformer I have used to convert 64-bit long ints to strings:
function longsToStrings(response) {
//console.log("transforming response");
var numbers = /("[^"]*":\s*)(\d{15,})([,}])/g;
var newResponse = response.replace(numbers, "$1\"$2\"$3");
return newResponse;
}
To add a transformer to the default list, say ahead of the JSON deserializer, you can do this:
$http.defaults.transformResponse.unshift(longsToStrings);
Resource 0: "f" 1: "a" 2: "l" 3: "s" 4: "e"
This finally worked for me:
transformResponse: function (data, headersGetter) {
return { isCorrect: angular.fromJson(data) }
}
Try using resource query method
https://github.com/angular/angular.js/issues/6314

Struggling with json array

Ive changed a json object recieved from an api and changed it to an array using $.makeArray and now im struggling to get values from this array. Im wanting temp_c and value within weather desc. A print out of the array is below.
[
Object
data: Object
current_condition: Array[1]
0: Object
cloudcover: "50"
humidity: "72"
observation_time: "10:25 AM"
precipMM: "0.1"
pressure: "1005"
temp_C: "13"
temp_F: "55"
visibility: "10"
weatherCode: "122"
weatherDesc: Array[1]
0: Object
value: "Overcast"
__proto__: Object
length: 1
__proto__: Array[0]
weatherIconUrl: Array[1]
winddir16Point: "SSW"
winddirDegree: "210"
windspeedKmph: "19"
windspeedMiles: "12"
__proto__: Object
length: 1
__proto__: Array[0]
request: Array[1]
__proto__: Object
__proto__: Object
You could try:
alert(yourObject.temp_C);
And
alert(yourObject.weatherDesc.value);
You wouldn't need to convert it to an array :)
You don't need to transform the object into an array, just access the properties you need:
var o = object_retrieved_from_api;
o.temp_c;
o.weatherDesc[0].value;
If you convert it into an array, just have to index first object in array:
var a = $.makeArray(object_retrieved_from_api);
a[0].temp_c;
a[0].weatherDesc[0].value;
The whole point of JSON is that it is already a Javascript object, so you don't need any complex parsing logic in order to get the data out. Try out the following code and you'll see how easy it is to get data from a JSON web service.
$.getJSON('your JSON URL here', function(data) {
$.each(data.current_condition, function() {
alert(this.temp_C + "C " + this.weatherDesc[0].value);
});
});

Categories