How to parse JSON with multiple rows/results - javascript

I don't know if this is malformed JSON string or not, but I cannot work out how to parse each result to get the data out.
This is the data.d response from my $.ajax function (it calls a WebMethod in Code Behind (C#)):
{"Row":[
{"ID1":"TBU9THLCZS","Project":"1","ID2":"Y5468ASV73","URL":"http://blah1.com","Wave":"w1","StartDate":"18/06/2015 5:46:41 AM","EndDate":"18/06/2015 5:47:24 AM","Status":"1","Check":"0"},
{"ID1":"TBU9THLCZS","Project":"2","ID2":"T7J6SHZCH","URL":"http://blah2.com","Wave":"w1","StartDate":"23/06/2015 4:35:22 AM","EndDate":"","Status":"","Check":""}
]}
With all the examples I have looked at, only one or two showed something where my 'Row' is, and the solutions were not related, such as one person had a comma after the last array.
I would be happy with some pointers if not even the straight out answer.
I have tried various combinations of response.Row, response[0], using $.each, but I just can't get it.
EDIT, this is my ajax call:
$.ajax({
url: "Mgr.aspx/ShowActivity",
type: "POST",
data: JSON.stringify({
"ID": "null"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var data = response.hasOwnProperty("d") ? response.d : response;
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#lblResErr').html('<span style="color:red;">' + thrownError);
}
});
At the moment I have just been trying to get ID1 value and ID2 value into the console.
EDIT (Resolved): Thanks to YTAM and Panagiotis !
success: function (response) {
var data = response.hasOwnProperty("d") ? response.d : response;
data = JSON.parse(data);
console.log(data);
}
Now the console is showing me an array of two objects, and now I know what to do with them !!

First you have to parse the string with JSON.parse
var data= JSON.parse(rowData);
Then you will get object like given below,
data = {
"Row": [
{
"ID1":"TBU9THLCZS",
"Project":"1",
"ID2":"Y5468ASV73",
"URL":"http://blah1.com",
"Wave":"w1",
"StartDate":"18/06/2015 5:46:41 AM",
"EndDate":"18/06/2015 5:47:24 AM",
"Status":"1",
"Check":"0"
},
{
"ID1":"TBU9THLCZS",
"Project":"2",
"ID2":"T7J6SHZCH",
"URL":"http://blah2.com",
"Wave":"w1",
"StartDate":"23/06/2015 4:35:22 AM",
"EndDate":"",
"Status":"",
"Check":""
}
]}
Here I am giving two options either direct retrieve data from data variable or through loop.
data.row[0].ID1
data.row[0].Project
data.row[0].ID2
and so on
OR
use loop,
var result = json.row;
for (var i = 0; i < result.length; i++) {
var object = result[i];
for (property in object) {
var value = object[property];
}
}
Hope this helps.

you may be getting a json string from the web method rather than an actual JavaScript object. Parse it into a JavaScript object by
doing
var data = JSON.parse(response);
then you'll be able to iterate over data.Row

Related

Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse(<anonymous>)

I'm working on an ajax call to an API. and upon calling this call, I keep running into this error. Please help. Ive been trying at this for hours and not sure what the issue is. Ive taken out the
JSON.parse and added them back to see if that will help but still no progress.
$.ajax({
type: "POST",
//url: 'http://aeM/api/getDataId',
url: '/bin/soupservice.getDataAccordToId.html',
//async: false,
data: IDschema,
//contentType: "application/json",
beforeSend: function () {
// Show image container
$("#wait").css("display", "block");
},
success:function (data, textStatus, jqXHR) {
console.log(jqXHR.status);
if (JSON.parse(data)) {
let fileDeviceData = [];
let uploadDate = [];
fileDeviceData = data;
let deviceNameFromFileData = [];
$.each(JSON.parse(data), function (i, element) {
dataInFile.push(element.file);
deviceNameFromFileData.push(element.deviceName);
//push an object while interacting with API. used to get similar index locations for later use
duplicateIdCheckedList.push({
"deviceName":element.deviceName,
"lastUploadDate":element.lastUploadDate.split(" ")[0] ,
"fileName": element.deviceName+ " "+element.lastUploadDate.split(" ")[0],
"id":element.id
});
let utcTime = element.lastUploadDate;
let utcText = moment(utcTime).format("L LT");
let anotherway = moment.utc(utcTime).local().format("L LT");
let firstConvertedString = anotherway.split("/").join("-").replace(",", "");
uploadDate.push(firstConvertedString.split(":").join("-").replace(",", ""));
})
//call on the findDuplicateIndex function to organize all the files that will be consolidated together
duplicates=findDuplicateIndex(duplicateIdCheckedList);
valuesforBrowserTime = uploadDate
exportAsTxt(deviceNameFromFileData, valuesforBrowserTime);
}
I see you are requesting a .html file and passing data to JSON.parse that expect a JSON format.
You may need to parse using a different method.

How to find the length of Success Data in Jquery Ajax?

I am retrieving list from ajax, when it become success, I wants to add those list values to DropDownList Items, So I want to iterate the data until last value and then add it to DropDownList
Here is my code What i tried
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "GPCreateCheque.aspx/getOpenRequestNo",
dataType: "json",
success: function (data) {
alert(data.length);
for (var i = 0; i<data.length; i++) {
$(".tbDDLReqNo").append(new Option(data.d[i], data.d[i]));
}
},
error: function (result) {
alert("Error");
}
})
In alert box it is showing undefined
UPDATE
I return the list<string> from [webmethod]
use data.d.length
alert(data.d.length);
for (var i = 0; i<data.d.length; i++) {
$(".tbDDLReqNo").append(new Option(data.d[i], data.d[i]));
}
You need to do data = JSON.parse(data); before treating your data like an array. It's just a string up to that point.
Update: if your data is not the array itself, but instead an object that contains an array named d, you need to work with that. It depends on your data structure.
Check the response from network tab in Chrome Developer Console or similar tool. May be response code is 200 but response data is missing.
On the other hand you want to itarete data in for loop but you try to append data.d[i]. If you want to append data.d[i] you have to itarete data.d in for loop.

AJAX - Extracting Info from JSON Object

I have data in a JSON object with the following format:
[{"Feature 1 Name":111,"Feature 2":111,"Feature 3":"stringforfeature3"}]
I've started to write some code to pull information from an API, but am not sure how to extract information (for instance, "stringforfeature3" if I somehow call "Feature 3") from the JSON object.
ajax: {
type: "GET",
url: '/api/apiname/info/moreinfo', //where i'm pulling info from
dataType: "JSON",
success: function(data, textStatus, jqXHR) {
return {
title: // Where I'd like to use the extracted information
};
}
},
Any advice would be greatly appreciated!
First of all, the response is an array, You need to get the first element like this
response = data[0];
Do you know each of the keys in advance? If yes,
{ title: response['Feature 3'] }
Else you can loop over response
for (var key in response) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + response[key]);
}
}
You should be able to extract the data using square bracket notation:
success: function(data, textStatus, jqXHR) {
return {
title: data[0]['Feature 3']
};
}
You result is an array, so I used data[0] to get the first item of array, or {"Feature 1 Name":111,"Feature 2":111,"Feature 3":"stringforfeature3"}.
In JavaScript you can access the same variable either using object.variable or object['variable']. Since your variable name has spaces, you are left with second option - data[0]['Feature 3']. Your result will be stringforfeature3.

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.

Javascript: Trouble parsing json response

Spring is returning a json-encoded object with four properties. One of which is a property named "array". I want the contents of this array.
Here's the whole json response:
ee
{"map":null,"array":[{"id":2,"description":"Cloud For Dev","businessSize":2,"businessType":9,"businessLocation":3},{"id":3,"description":"Cloud For Prod","businessSize":2,"businessType":9,"businessLocation":3}],"string":null,"bool":false}
0
I'm not actually sure what the "ee" or 0 mean... Anyway, I'm trying to parse it like this:
$.ajax({
type: "GET",
url: "/ajax/rest/teamService/list",
dataType: "json",
success: function (response) {
var teamArray = response.array;
var $el = $("#teamSelect");
$el.empty();
$.each(teamArray[0], function(team) {
alert(team.description);
$el.append($("<option></option>").attr("value", team.id).text(team.description));
});
// Reattach the plugin
$("#teamSelect").selectbox("detach");
$("#teamSelect").selectbox("attach");
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus === 'error') {
setTimeout(function() { window.location = '/do/login'; }, 7000);
}
}
});
And I'm getting the alert box pop up 6 times (should be 2), and each time it says "undefined" rather than the actual description.
The select box itself has four empty options.
Seems like I'm iterating over the json encoded object's four parameters, NOT the two contents of the enclosed array.
How can I fix this?
Try this - teamArray[0] should be only teamArray
$.each(teamArray, function(i,team) {
alert(team.description);
$el.append($("<option></option>").attr("value", team.id).text(team.description));
});
Right now, you're looping over the keys of teamArray[0], hence the six alerts. Loop over teamArray. Also, $.each's callback takes indexInArray, valueOfElement. May as well not jQuery through that:
for(var i = 0; i < teamArray.length; i++) {
var team = teamArray[i];
...
}

Categories

Resources