Decode Json Response from Ajax Call - javascript

I am getting a json response from python script via a ajax call on my html page, which I am running on localhost. When I alert/display the response it is in proper ajax format but I don't know how to decode it. JSON parse display [object] [object]. Any help? Thanks in advance.
HTML:
function getData() {
// Code doesn't even enter this function but when i remove the $.ajax part it enters the function
alert("I AM HERE");
$.ajax({
type: "GET",
datatype: 'json',
url: "/cgi-bin/check.py",
data: {
action: 'muawia()',
},
success: function(data) {
alert(data);
},
error: function(data) {
alert(data.responseText);
}
});
};
Python:
#!/usr/bin/python
import cgi, cgitb
from StringIO import StringIO
import json
class myclass:
def __init__(self):
self.data = []
def muawia(self):
content=json.loads('{"access": {"token": {"issued_at": "2013-04-18T14:40:23.299903", "expires": "2013-04-19T14:40:23Z", "id": "4c5ef01f52c7404fb5324c520d25d1fe", "tenant": {"description": "admin tenant", "enabled": true, "id": "51ad87714b86442d9a74537d6f890060", "name": "admin"}}, "serviceCatalog": [{"endpoints": [{"adminURL": "http://10.199.0.250:8774/v2/51ad87714b86442d9a74537d6f890060", "region": "RegionOne", "internalURL": "http://10.199.0.250:8774/v2/51ad87714b86442d9a74537d6f890060", "id": "9869f55f0de2490685676b6ec27f6097", "publicURL": "http://10.199.0.250:8774/v2/51ad87714b86442d9a74537d6f890060"}], "endpoints_links": [], "type": "compute", "name": "nova"}, {"endpoints": [{"adminURL": "http://10.199.0.250:8080", "region": "RegionOne", "internalURL": "http://10.199.0.250:8080", "id": "321601d827ba4bbbb6de1df69fd43a1c", "publicURL": "http://10.199.0.250:8080"}], "endpoints_links": [], "type": "s3", "name": "swift_s3"}, {"endpoints": [{"adminURL": "http://10.199.0.250:9292", "region": "RegionOne", "internalURL": "http://10.199.0.250:9292", "id": "cca7d7a24dbe45b6ae08da2c023b0d82", "publicURL": "http://10.199.0.250:9292"}], "endpoints_links": [], "type": "image", "name": "glance"}, {"endpoints": [{"adminURL": "http://10.199.0.250:8776/v1/51ad87714b86442d9a74537d6f890060", "region": "RegionOne", "internalURL": "http://10.199.0.250:8776/v1/51ad87714b86442d9a74537d6f890060", "id": "14773153229d4e7f80e47cf7b1dd2d15", "publicURL": "http://10.199.0.250:8776/v1/51ad87714b86442d9a74537d6f890060"}], "endpoints_links": [], "type": "volume", "name": "cinder"}, {"endpoints": [{"adminURL": "http://10.199.0.250:8773/services/Admin", "region": "RegionOne", "internalURL": "http://10.199.0.250:8773/services/Cloud", "id": "064df72a67f54dffa68c07b8fc400bdb", "publicURL": "http://10.199.0.250:8773/services/Cloud"}], "endpoints_links": [], "type": "ec2", "name": "nova_ec2"}, {"endpoints": [{"adminURL": "http://10.199.0.250:8080/", "region": "RegionOne", "internalURL": "http://10.199.0.250:8080/v1/AUTH_51ad87714b86442d9a74537d6f890060", "id": "194df182a8c043e48175a40fb615064e", "publicURL": "http://10.199.0.250:8080/v1/AUTH_51ad87714b86442d9a74537d6f890060"}], "endpoints_links": [], "type": "object-store", "name": "swift"}, {"endpoints": [{"adminURL": "http://10.199.0.250:35357/v2.0", "region": "RegionOne", "internalURL": "http://10.199.0.250:5000/v2.0", "id": "34db74b5f32f4121932725b1146a1701", "publicURL": "http://10.199.0.250:5000/v2.0"}], "endpoints_links": [], "type": "identity", "name": "keystone"}], "user": {"username": "admin", "roles_links": [], "id": "b5902682120742baa150945d8a37ff47", "roles": [{"name": "admin"}], "name": "admin"}, "metadata": {"is_admin": 0, "roles": ["9aa2eb385f4e4a8e80ad5002c212e76b"]}}}')
data=json.dumps(content, indent=4, separators = (', ', ': '))
print data
return
print "Content-Type: text/html\n"
x = myclass()
x.muawia()

You should use
console.log(data)
rather than alert(data). Alert will only show you strings

alert() only outputs strings. So generally it would be the same as:
data = data.toString();
alert(data);
Use console.log or console.dir in combination with JSON.parse to show the actual object that is returned from the JSON.parse.
// In your $.ajax success method
var someVar = JSON.parse(data);
console.log(someVar);
You can also set it to a global variable temporarily to debug it via the Firebug/Chrome DevTools console by typing its name. For example:
// In your $.ajax success method
window.data = data;
And then type "data" in your console.
Please note that this is a bad practice to ship to production, global variables cannot be garbage collected by your browsers JavaScript engine and especially a global variable name as data has a high possibility of turning into a conflict with other global variables. If you still want to use a global for some reason then make sure you use a solid naming convention to prevent error.

That's absolutely normal as JSON.parse(stringData) create s normal JavaScript object, so you get the [object Object] in the alert. You have to access each object's property to get its value. In your case
var jsonObj = JSON.parse(data);
alert(jsonObj.access.token.issued_at);
will be for instance "2013-04-18T14:40:23.299903"

You can use $.parseJSON to format your data correctly. You may also want to remove the extra comma at the end of your error response function. It can cause syntax errors. Remove the comma from "action: 'muawia()'," as well.
success: function(data){
r = $.parseJSON(data)
alert(r.responseText);
},
error: function(data){
r = $.parseJSON(data)
alert(r.responseText);
}
Hope this helps!

Related

Unable to iterate the response body and manipulate/filter the response object using node JS

I have below code which is going to invoke REST endpoint and return response back. I just tried to print the response.body in the console and It works perfectly fine.
var express = require('express');
var app = express();
var PORT = 8001;
var request = require('request');
var HashMap = require('hashmap');
var endPoint="http://sandbox.dev.amazon.com/idsearch/environment/amazon/";
app.get('/productId/:proId',async (req,res) => {
try
{
var headers ={
"accept":"application/json"
}
var options = {
url:endPoint.concat(req.params.proId),
headers:headers
}
request(options, (error,response,body)=> {
console.log(response.body) // It returned response as below output JSON file
res.send("STATUS CODE : 200");
});
}
catch(error)
{
throw error;
}
});
Output:
{
"<Some dynamic Content>": {
"type": "PROD-ID",
"environment": "amazon",
"tags": [
{
"name": "EC-6S0005704A8324S98020",
"source": "amazonstage2ma_paymentapiplatserv#TOKEN",
"flags": [
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary": [
{
"pool": "slingshotrouter",
"machine": "stage21007",
"apiName": "GET",
"status": "0",
"duration": 13400.0,
"link": "https://www.amazon.qa.pilot.com/Tid-942342192424j2j234"
},
{
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "1",
"duration": 13368.0,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"pool": "devstage_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "1",
"duration": 15.0,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
],
"partial": false
}
}
The above output contains all the responses with respective Endpoint URL which is expected. But I just want to fetch only the object contains "Status: 1". I'm just wondering that How can I manipulate the response.body object to get the below JSON as output.
Expected Output:
{
"callSummary":[
{
"pool": "slingshot",
"machine": "stage21029",
"apiName": "GET",
"status": "1",
"duration": 13368.0,
"link": "https://www.amazon.qa.pilot.com/Tid-12342342i842424j2j234"
},
{
"pool": "devstage_userbridgedomainserv",
"machine": "amazon1int-g_userbridgedomainserv_22",
"apiName": "POST",
"status": "1",
"duration": 15.0,
"link": "https://www.amazon.qa.pilot.com/Tid-02341723424i842424j2j290"
}
]
}
I just want to iterate the response.body obj and check the status as 1 if it's then I need to fetch all the details and form it as above payload. This is dynamic content but the template format is static.
I tried the below code to iterate the response.body but no luck.
var string = JSON.stringify(response.body);
var objectValue = JSON.parse(string);
var obj = objectValue.callSummary;
console.log(obj.length); // It returned undefined.
Please lead me to achieve this.
To return that json, just
res.json(response.body['<Some dynamic Content>'].callSummary);
Adding some validation and error handling would be a good idea before sending the response.
In case your key is just an example and you never know your first key value, and you always want the values of the first key
res.json(Object.values(response.body)[0].callSummary);
Object.values returns an array, so you can iterate the values if you want manage more than the first one

Ajax Post JSON with circular reference

I have the following JSON
"node": {
"id": "812de6d0-a754-11e7-a7d4-47a3233fb668",
"name": "123",
"type": "node",
"children": [
{
"id": "d517b899-d211-4896-8eeb-466268ddf2e3",
"name": "456",
"type": "node",
"children": [
{
"id": "a913ce08-aff7-446b-a996-ba5a14939dd1",
"name": "789",
"type": "node",
"children": [],
"parent": "d517b899-d211-4896-8eeb-466268ddf2e3"
}
],
"parent": "812de6d0-a754-11e7-a7d4-47a3233fb668"
}
],
}
which, obviously, has a circular reference on the children attribute. As you may assume, this is a "one-to-many" relationship and my backend is expecting the data in this way.
My question is: is there any way to post the data like this using ajax? I tried circular-json and cycle.js from Douglas Crockford but I got no success. Both libraries are not returning the same object when I restore it.
Ajax post:
$.ajax({
url: requestURL,
type: requestType, // POST
data: payload, // variable contains the JSON
success: function(data) {
console.log("success!");
},
error: function(error){
console.log(error);
}
});
Thanks very much for the help!
Solved it removing the circular references as pointed out by #kevinb

Output JSON data using Jquery GET

I'm using Jquery GET to fetch some JSON data that looks like this:
{
"list": {
"meta": {
"type": "resource-list",
"start": 0,
"count": 1
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"change": "-0.400002",
"chg_percent": "-1.200485",
"day_high": "33.779999",
"day_low": "32.549999",
"issuer_name": "PayPal Holdings, Inc.",
"issuer_name_lang": "PayPal Holdings, Inc.",
"name": "PYPL",
"price": "32.919998",
"symbol": "PYPL",
"ts": "1442606400",
"type": "equity",
"utctime": "2015-09-18T20:00:00+0000",
"volume": "16488139",
"year_high": "42.550000",
"year_low": "30.000000"
}
}
}
]
}
}
I would like to get the value of day_high. Using Jquery I do:
jQuery.ajax({
url: "http://****.com",
type: "GET",
dataType: "json",
async: false,
success: function (data) {
var x = JSON.stringify(data.list.resource.change);
$("p.name").append(x);
console.log(x.change);
}
});
In my console I get:
Uncaught TypeError: Cannot read property 'change' of undefined
I also tried an array approach like data.list.resource[0].change But this outputs:
Uncaught TypeError: Cannot read property '0' of undefined
First, the variable x cannot be interpreted as JSON with your console logging statement because JSON.stringify converts it to a string. Second, it looks like you have your path mixed up. It should be data.list.resources[0].resource.fields.change.
You can try this:
var x = JSON.stringify(data.list.resources[0].resource.fields.change);
The error was with your path.

Iterate through nested Javascript Objects from API response

I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);

parse facebook json javascript

I am using javascript api to get facebook comments.
i am getting the following json result , but how can i parse them to use on my page ?
{
"id": "1234567891_2823098717038_3160191",
"from": {
"name": "User",
"id": "1234567891"
},
"message": "comment only...",
"can_remove": true,
"created_time": "2012-05-05T07:43:11+0000"
},
{
"id": "1234567891_2823098717038_3160281",
"from": {
"name": "User",
"id": "1234567891"
},
"message": "just another comment...",
"can_remove": true,
"created_time": "2012-05-05T08:14:17+0000"
},
{
"id": "1234567891_2823098717038_3160336",
"from": {
"name": "user2",
"id": "56265654845454"
},
"message": "congratz dear :)",
"can_remove": true,
"created_time": "2012-05-05T08:29:05+0000"
}
],
"paging": {
"next": "http://link.dddd"
}
}
How can i loop through this and display the contents ?
jQuery solution is acceptable.
Thank you.
Use JQuery.parseJSON: http://api.jquery.com/jQuery.parseJSON/
assoc_data = jQuery.param(response); //where response is your json
$.ajax({
type: "POST",
url: "submit_fb_data.php",
data: assoc_data,
success: function(data) {
//etc
}
});
make sure you use a >=1.4 jquery version

Categories