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.
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);
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.
I have a valid JSON result:
{
"metadata": [
{
"name": "md1",
"value": "blah1"
},
{
"name": "md2",
"value": "blah2"
},
{
"name": "tee2",
"value": "blah3"
}
],
"subdata1": [
{
"name": "sd1_1",
"value": "blah1_1"
},
{
"name": "sd1_2",
"value": "blah1_2"
},
{
"name": "sd1_3",
"value": "blah1_3"
},
{
"name": "sd1_4",
"value": "blah1_1"
}
],
"subdata2": [
{
"name": "sd2_1",
"value": "blah2_1"
},
{
"name": "sd2_2",
"value": "blah2_2"
},
{
"name": "sd2_3",
"value": "blah2_3"
}
]
}
coming in via a successful jQuery .ajax() call:
$.ajax({
url: 'test.json',
type: 'get',
datatype: 'json',
processData: false,
success: function(data) { //do something...};
It's relatively easy to blob the entire result into a value associated with an overall key:
localStorage.setItem('newtest', data);
This would save the entirety of my JSON response as a value with a key called "newtest". But suppose I want each array's descriptor as the key name and the associated array as the value? In my example, that would give me three key/value pairs, with each array saved as a separate string value associated with keys named "metadata," "subdata1" and "subdata2", respectively. I've done a great deal of searching but have not come across the correct approach for this. Any help towards a solution would be greatly appreciated -- thank you for your attention and assistance.
You can do a for loop and stringify the objects.
$.ajax({
url: 'test.json',
type: 'get',
datatype: 'json',
processData: false,
success: function(data) {
for(var key in data){
localStorage.setItem(key, JSON.stringify(data[key]));
}
}
});
Then parse when you get them
JSON.parse(localStorage.getItem("metadata"));
I have the following ajax request...
Ajax
function initUpdate()
{
var id = $(this).attr('id').split('_')[1];
//grab id from link update_xxxx
//get all gallery information
$.ajax(
{
type: 'POST',
url: 'ajax/update',
data: {"id": id},
dataType: 'json',
success: function(json)
{
//query was successful now populate form
$("input[name='galleryName']").val(/*what goes here?*/);
}
});
}
That returns the following data
{
"selected_gallery": [
{
"id": "4004",
"name": "Album Proofer Sample Gallery",
"clientRef": "205",
"clientName": "Mike "
}
]
}
How would I access "name" to insert in the val()?
Thanks!
What have you tried? I would think you could get to it via:
json.selected_gallery[0].name
selected_gallery is a JavaScript array, so you would access the first item in the collection using [0] in order access the first item's properties.
UPDATE
You could access other items in the array if they existed:
{
"selected_gallery": [
{
"id": "4004",
"name": "Album Proofer Sample Gallery",
"clientRef": "205",
"clientName": "Mike "
},
{
"id": "5005",
"name": "blah",
"clientRef": "405",
"clientName": "Dave "
},
{
"id": "6006",
"name": "boo",
"clientRef": "605",
"clientName": "Doug"
}
]
}
To get the second item in the array, you'd reference it as:
json.selected_gallery[1].name (or id or clientRef or ...). You can get to the third item via json.selected_gallery[2].name.
Hope this helps.