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.
Related
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
i wondering if there any solution to get data from json in this format:
{ "#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">":[{"id":68,
"name":"johnny",
"description":"Hello my first Description",
"created_by_user_id":16530,
"created_at":"2016-01-28T13:17:51.827Z",
"updated_at":"2016-01-29T10:40:40.011Z",
"receiver_group_id":3,"dynamic_fields":{
"files":[
{
"id":2,
"date":"2016-01-29T10:40:35.720Z",
"path":"http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
"public":null
}
]} }]}
like i want to have a name and description. but if i call in ajax like this:
$(function(){
$.ajax({
url: './dataModel.json',
dataType: 'json',
method: 'GET',
success: function(data){
console.log(data[0].name);// error name is not defined
console.log(data.name); // undefined
}
});
})
may be you guys have some idea how can i get the name and description? thank you so much for any kind of suggestion and idea.
best regard,
ape
Try this:
var input = {
"#<Hashie::Mash acceptance_type=1 id=79 name=\"template 1\" url=\"http://myDomain\">": [{
"id": 68,
"name": "johnny",
"description": "Hello my first Description",
"created_by_user_id": 16530,
"created_at": "2016-01-28T13:17:51.827Z",
"updated_at": "2016-01-29T10:40:40.011Z",
"receiver_group_id": 3,
"dynamic_fields": {
"files": [{
"id": 2,
"date": "2016-01-29T10:40:35.720Z",
"path": "http://mayDomain/000/000/002/original/The_Idiot.pdf?1454064035",
"public": null
}]
}
}]
};
var output = Object.keys(input).map(function(key) {
return input[key];
})[0];
alert(output[0].name);
Here is my Json Data received from Server:
[
{"Name":"A"},
{"Name":"B"},
{"Name":"C"},
{"Name":null}
]
[
{"Name":null},
{"Name":"D"},
{"Name":null}
]
[
{...},
{...}
]
How do I parse it using using JQUERY in AJAX success attribute?
Here is my Ajax code:
$.ajax({
url: '#.php',
type: 'post',
async: false,
data: {},
dataType: 'json',
success: function(data){
var str = JSON.stringify(data);
var obj = JSON.parse(str);
for(var i=0; i< data.length;i++)
{
alert(data[i].Name);
}
},
complete: function(xhr,status){
alert(status);
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText );
alert("An error occured. Please Try Again");
}
})
This code is not working and giving parser error on complete.
I want to Display all the Names received.
Please Help.
your data received from the server are not valid JSON, if it was, it would be
something like :
[
[{
"Name": "A"
}, {
"Name": "B"
}, {
"Name": "C"
}, {
"Name": null
}],
[{
"Name": null
}, {
"Name": "D"
}, {
"Name": null
}]
]
that would be even easier to parse:
[{
"Name": "A"
}, {
"Name": "B"
}, {
"Name": "C"
}, {
"Name": null
}, {
"Name": null
}, {
"Name": "D"
}, {
"Name": null
}]
The data returned by your server does not respect JSON syntax.
In order to have a proper JSON structure, there should be only one parent object and not multiple arrays.
If you can modify your server's output, consider the following alternatives:
Creating a parent array:
[ your_arrays ]
then access to data[0] to retrieve your arrays in your success function.
Creating a parent object:
{myArrays : your_arrays}
then access to data.myArrays in your success function.
please help to bring the console dataset.
I do Ajax request and receive a response date as an array:
[{"pk": 2, "model": "app_accounts.userprofile", "fields": {"phone": "21", "other": "<p>qqqqqqdfgdfg</p><p><b>fdg</b></p>", "user_permissions": [], "avatar": "", "skype": "dfsdf", "gender": 2, "groups": []}}]
the problem is that the console does not work and bring
data.pk
and
data.model
screenshot here
$.ajax({
url: "/search_author/",
type: 'POST',
dataType:"json",
data: {
"author": $('#formSearchAuthorWord').val(),
"csrfmiddlewaretoken": $.csrf_token
},
success: function(data) {
console.log(data)
console.log(data.pk)
console.log(data.model)
}
});
That's because it's inside the array.. access them like:
data[0].pk
data[0].model
"[]" brackets represents an array and "{}" an object.
See the DEMO here
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!