extract data from json - json
I have a json data coming from wcf servicein jquery like this
GetBedTypeList1Result1 is function in wcf
{
"GetBedTypeList1Result":[
{"Code":23,"CompanyCode":null,"Decode":"1 Class New Born Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0},
{"Code":22,"CompanyCode":null,"Decode":"1st Class Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0},
{"Code":5,"CompanyCode":null,"Decode":"Classique Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0}
],
"strErrMsg":"Y",
"chrErrFlg":"c"
}
I am calling service like below
function CallWcfService() {
//alert("CallWcfServicexxxx");
jQuery.ajax
(
{
type: Type,
url: Url,
data: parameters,
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
cache: "false",
crossDomain: true, //Same result if i remove this line
processdata: ProcessData, //True or False
success: function (msg)
{
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
}
);
}
function callService()
{
DataType = "json";
Type = "GET";
var par = 4;
parameters = null;
Url = "http://192.168.2.42/CWSERVERWCF/bedtypemasterService.svc/GetBedTypeList?callback=?";
parameters = "{'strErrMsg':'1'},{'chrErrFlg':'A'},{'pcompanycode':'0'},{'pdiv':'1'},{'ploc':'1'}";
// alert(parameters);
ContentType = "application/json; charset=utf-8";
ProcessData = true;
//alert("sssssasasadsds");
CallWcfService();
}
I am trying to fetch data but not getting lke below
function ServiceSucceeded(result)
{
if (DataType == "json")
{
var obj = jQuery.parseJSON(JSON.stringify(JSON.stringify(result)));
for (var x = 0; x < obj.length; x++)
{
}
}
}
In obj.length count of characters is coming and jQuery.parseJSON(result) is not working
Please help
If the result is json there is no need to parse it in this way. jQuery.ajax will return a javascript object if the datatype is set to json.
So in your ServiceSucceeded function you may operate on the result variable directly. If you are trying to iterate over the bed types change your for loop to something like this:
for (var i = 0; i < result.GetBedTypeList1Result.length; i++) {
// ...do stuff
// var bed = result.GetBedTypeList1Result[i]]
}
Try using JSON.parse(result) instead of: var obj = jQuery.parseJSON(JSON.stringify(JSON.stringify(result)));
Also, since you've mentioned the dataType as 'json' in your $.ajax call, your response should already be in JSON format with no parsing required.
Related
Parsing json string from events(function) ajax in Full Calendar
I have no clue on how to parse events in full calendar events: function(start, end, timezone, callback) { $.ajax({ url: 'async/form.php?a=liste_consignes', datatype:'json', data: { // our hypothetical feed requires UNIX timestamps start: start.unix(), end: end.unix() }, success: function(msg) { //not sur then how to parse var events = msg.events; callback(events); //this gives error }, }); } PHP (part of) while($row = $query->fetch_assoc()) { $cal['id'] = $row['consigne_id']; $cal['title'] = $row['contenu']; $cal['start'] = $row['date_consigne']; array_push($return_arr,$cal); } echo json_encode($return_arr); PHP is returning [{"id":"5","title":"consigne","start":"2019-03-03"},{"id":"6","title":"test","start":"2019-03-02"},{"id":"7","title":"test 2","start":"2019-03-02"}] I tried several way from events as json feed but none of them are returning something
PHP is returning an array. It doesn't have an events field. If your callback is meant to consume an array, simply call callback(msg)
Solution was to convert json string from php to object success: function(msg) { var events = []; var data = jQuery.parseJSON(msg); $.each(data, function(i, item) { events.push({ title: item.title, start: item.start, // will be parsed end: item.end, // will be parsed }); }); callback(events); }
How can i remove escape sequences to format into proper json?
I am passing an array of strings to the server in post. This string is actually an object converted to string using json.stringify var editedRows[]; editedRows.push(117); editedRows.push(123); var dataItems = []; for (var i = 0; i < editedRows.length; i++) { var item = grid.dataSource.get(editedRows[i]); dataItems.push(JSON.stringify(item)); } var model = JSON.stringify({ 'model': dataItems }); $.ajax({ contentType: 'application/json; charset=utf-8', dataType: 'json', type: 'POST', url: "#Url.Action("SaveResults", "Maps")", data: model , success: function () { }, failure: function (response) { } }); My controller code is public int SaveResults(List<string> model) { foreach (var s in model) { var serializer = new JsonSerializer(); ShortDetail shortDetail = serializer.Deserialize<ShortDetail>(new JsonTextReader(new StringReader(s))); } return 0;} On server side (value of s is), i receive "{\"firstname\":\"Jacob\",\"surname\":\"Price\",\"preferredname\":\"\",\"classid\":114,\"classname\":\"5 A\",\"studentid\":140,\"Age\":\"12y4m\",\"male\":true,\"indicatorID\":null,\"indicatorDescription\":null,\"results\":[{\"ResultID\":11741,\"StudentID\":140,\"ClassID\":114,\"YearID\":22,\"assessmentId\":49,\"ResultValue\":\"94.0\",\"shortdescription\":\"Accuracy %\",\"Term\":1,\"Month\":0,\"Week\":0,\"Semester\":1,\"ResultTypeID\":14,\"NotesLong\":\"{\\\\rtf1\\\\ansi\\n{\\\\rtf1\\\\ansi\\n{\\\\pard\\n{\\\\pard\\\\par}\\n\\n\\\\par}\\n\\n}\\n}\",\"Color\":\"ffc080\",\"AllowNumber\":true,\"AllowLetter\":false,\"AllowAll\":false,\"AgeLevel\":false,\"SelectFromList\":false,\"RowOrder\":17,\"MinNumber\":0,\"MaxNumber\":100,\"DecimalPoints\":null,\"AllowedValues\":\"\",\"ColumnAlignment\":2,\"ColumnWidth\":20,\"Updated\":true,\"InActive\":false,\"SchoolID\":0,\"FormattingEnabled\":true,\"AssessmentName\":\"LITERACY - PROBE Fiction\",\"YearTermSemester\":\"2015 S1 T1\",\"MaxLength\":\"0 - 100\",\"MapDetailId\":2532},{\"ResultID\":11741,\"StudentID\":140,\"ClassID\":114,\"YearID\":22,\"assessmentId\":49,\"ResultValue\":\"13.0-14.0\",\"shortdescription\":\"Read Age\",\"Term\":1,\"Month\":0,\"Week\":0,\"Semester\":1,\"ResultTypeID\":22,\"NotesLong\":\"{\\\\rtf1\\\\ansi\\n{\\\\rtf1\\\\ansi\\n{\\\\pard\\n{\\\\pard\\\\par}\\n\\n\\\\par}\\n\\n}\\n}\",\"Color\":\"ffffff\",\"AllowNumber\":false,\"AllowLetter\":false,\"AllowAll\":true,\"AgeLevel\":false,\"SelectFromList\":false,\"RowOrder\":23,\"MinNumber\":0,\"MaxNumber\":0,\"DecimalPoints\":null,\"MapDetailId\":2532}]}" While expected is {"firstname":"Jacob","surname":"Price","preferredname":"","classid":114,"classname":"5 A","studentid":140,"Age":"12y4m","male":true,"indicatorID":null,"indicatorDescription":null,"results":[{"ResultID":11741,"StudentID":140,"ClassID":114,"YearID":22,"assessmentId":49,"ResultValue":"94.0","shortdescription":"Accuracy %","Term":1,"Month":0,"Week":0,"Semester":1,"ResultTypeID":14,"NotesLong":"{\\rtf1\\ansi\n{\\pard\n{\\pard\\par}\n\n\\par}\n\n}","Color":"FFC080","AllowNumber":true,"AllowLetter":false,"AllowAll":false,"AgeLevel":false,"SelectFromList":false,"RowOrder":17,"MinNumber":0,"MaxNumber":100,"DecimalPoints":null,"AllowedValues":"","ColumnAlignment":2,"ColumnWidth":20,"Updated":true,"InActive":false,"SchoolID":0,"FormattingEnabled":true,"AssessmentName":"LITERACY - PROBE Fiction","YearTermSemester":"2015 S1 T1","MaxLength":"0 - 100","MapDetailId":2532},{"ResultID":11741,"StudentID":140,"ClassID":114,"YearID":22,"assessmentId":49,"ResultValue":"13.0-14.0","shortdescription":"Read Age","Term":1,"Month":0,"Week":0,"Semester":1,"ResultTypeID":22,"NotesLong":"{\\rtf1\\ansi\n{\\pard\n{\\pard\\par}\n\n\\par}\n\n}","Color":"FFFFFF","AllowNumber":false,"AllowLetter":false,"AllowAll":true,"AgeLevel":false,"SelectFromList":false,"RowOrder":23,"MinNumber":0,"MaxNumber":0,"DecimalPoints":null,"AllowedValues":"4.5-5Û4.5Û","ColumnAlignment":0,"ColumnWidth":10,"Updated":true,"InActive":false,"SchoolID":0,"FormattingEnabled":false,"AssessmentName":"LITERACY - PROBE Fiction","YearTermSemester":"2015 S1 T1","MaxLength":"Any value","MapDetailId":2532},{"ResultID":11741,"StudentID":140,"ClassID":114,"YearID":22,"assessmentId":49,"ResultValue":"10.00","shortdescription":"Stud Age","Term":1,"Month":0,"Week":0,"Semester":1,"ResultTypeID":23,"NotesLong":"{\\rtf1\\ansi\n{\\pard\n{\\pard\\par}\n\n\\par}\n\n}","Color":"FFFFFF","AllowNumber":true,"AllowLetter":false,"AllowAll":false,"AgeLevel":false,"SelectFromList":false,"RowOrder":24,"MinNumber":0,"MaxNumber":0,"DecimalPoints":null,"AllowedValues":"","ColumnAlignment":0,"ColumnWidth":8,"Updated":true,"InActive":false,"SchoolID":0,"FormattingEnabled":false,"AssessmentName":"LITERACY - PROBE Fiction","YearTermSemester":"2015 S1 T1","MaxLength":"1 - 17","MapDetailId":2532},{"ResultID":11741,"StudentID":140,"ClassID":114,"YearID":22,"assessmentId":49,"ResultValue":"Green Star - Blank","shortdescription":"Hom Lev Pr","Term":1,"Month":0,"Week":0,"Semester":1,"ResultTypeID":24,"NotesLong":"{\\rtf1\\ansi\n{\\pard\n{\\pard\\par}\n\n\\par}\n\n}","Color":"FF8080","AllowNumber":false,"AllowLetter":false,"AllowAll":false,"AgeLevel":false,"SelectFromList":true,"RowOrder":25,"MinNumber":0,"MaxNumber":0,"DecimalPoints":null,"AllowedValues":"Gold StarÛ1ÛÛRed Green DotÛ2ÛÛBlue StarÛ3ÛÛBronze StarÛ4ÛÛGreen Star - BlankÛ5Û","ColumnAlignment":0,"ColumnWidth":8,"Updated":true,"InActive":false,"SchoolID":0,"FormattingEnabled":true,"AssessmentName":"LITERACY - PROBE Fiction","YearTermSemester":"2015 S1 T1","MaxLength":"Select from list","MapDetailId":2532},{"ResultID":11741,"StudentID":140,"ClassID":114,"YearID":22,"assessmentId":49,"ResultValue":"2","shortdescription":"Determ Set","Term":1,"Month":0,"Week":0,"Semester":1,"ResultTypeID":25,"NotesLong":"{\\rtf1\\ansi\n{\\pard\n{\\pard\\par}\n\n\\par}\n\n}","Color":"FFFFFF","AllowNumber":false,"AllowLetter":false,"AllowAll":false,"AgeLevel":false,"SelectFromList":true,"RowOrder":26,"MinNumber":1,"MaxNumber":20,"DecimalPoints":null,"MapDetailId":2532}]} How can i remove escape sequences to format into proper json?
This was really my bad...I was doing JSON.stringify in another function before passing the item..so it was being stringified thrice :(..Now all good!
Not Able To Parse Web Response Content
I'm trying to retrieve JSON from a URL and read it into my application. I am having an issue when reading the WebResponse. When the response is read, it comes back as only Symbols and is not properly formatted json. How do I get a properly formatted JSON after streaming my WebResponse? My Javascript is as follows: function getJsonWM() { //var stringedData = JSON.stringify(ajaxData); $.ajax({ type: "GET", url: '/Default/GetQuestionByHighestScore', //data: JSON.stringify("{}"), contentType: "application/json; charset=utf-8", //dataType: "json", success: function (data) { var label = $("#lblResults"); var json = JSON.stringify(data); label.text(json); //if (data.d.Pin == undefined) { // alert("Error: " + data.d.ErrorMessage); //} else { // alert("Please record the following PIN: \r\n \r\n" + data.d.Pin); //} }, error: function (data) { //alert("Error: " + data.d.ErrorMessage); } }); } $(function() { //$("#btnSubmit").click(getJson); $("#btnSubmit").click(getJsonWM); }); My controller is as follows: public class DefaultController : Controller { private const string questionUrl = "https://api.stackexchange.com/2.1/questions?order=desc&sort=activity&site=stackoverflow"; public string GetQuestionByHighestScore() { List<Item> list = new List<Item>(); var json = GetJson(questionUrl); var array = JsonConvert.DeserializeObject<Item>(json); return list.OrderByDescending(x => x.Score).FirstOrDefault().ToString(); } public string GetJson(string url) { var myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); myWebRequest.Method = "GET"; myWebRequest.ContentType = "application/json"; var myWebResponse = (HttpWebResponse)myWebRequest.GetResponse(); string strResponse = String.Empty; var encoding = Encoding.Default; using (var reader = new StreamReader(myWebResponse.GetResponseStream(), encoding)) { //JavaScriptSerializer js = new JavaScriptSerializer(); strResponse = reader.ReadToEnd(); } return strResponse; } } My strResponse object is as follows: "‹\b\0\0\0\0\0\0µ\\\vÛ6¶þ+„\bÚ{G£%Q)‚ÜI“4\t6»iÓtw/”HÙšÑÕä™8Eÿû=‡”ly,y$·iÐ%òóññ¼éßi#ózñô[4|‰wÑe!›ÅÅ\"ßdMÚ¬*ÉEZ,ÿw±(ï\vY-žþ¶¨äzÓð&-‹ÅSÛv/›ZVשX<umæYžÝ¾i¶k¹x\nÝ—iÝÈJ\n`ËãX®›ëŠ7ÐÄØÅb]•IšÉë4çKì½jšuýÔ4Ó˺áñíeš/7Õe\\ææÏôêþß—7ëåóú™í°'Ëg60i½Îøöºà9’¼ÝþÄsÙÅ\"K‹Û–!ðSÜÊ;Y%Yy¯øák³²Yßn+EøûÅ\"¯yQß«!?MxVË‹Å]*ï¯ãrS40i\a&¢:ìÞ\\,긬`|1¯›k7é]Úl¯…šªM=›:®ãBÏW¯ßd‡¡¶¤R¤Í™Öô׬™Zih`®CŸfGSmiLµ·Æns\r؃Ï[#^ÉøVVFÝȸ1Š²1jÙMiðÂH\và\\ÄÒ(|Ô}`‘#®û{ÅòçŽ%Q,IË’ü]u'À’\0KÒ”„¤cIÊ[–¿_ìÁ˜oë_3ø’uY7ËJê\ažó/eaÀÞÔ«4iF‘é[¬‡L'p=Ë\n§\"3\bÆ‘y¹¬øo¸¦þhºŒ\a¡—D‚òÀŠBG¸’{^苘E2òe\v[ñ,²hÒ¸,žTÏ>üð$Âñ\aÞ4+m–“ÜÎÐ\\ï(§ ù!©#v¼a ·MG`\rÄsÁŠ4fšÃFÜIc\rÝÊ*ï#\bs4 wµ565b¸*ïb“G\0„=*ßjZÒ£E´-Q´DÑ ½niûð[o›•’$u\t(nêq!Ø—¥>sN!m\fXÙÊ¿\\–å2“H\nøh\0'jYŒ¼æÅ««7âêyµû¯÷ùÅ'35~i^_Õ/£[s½*›RËÊ/ˆºc€}¿ªÒšü$y6aíÌÌIá\0鈹gcÌG0qTXj²caÉ|¶°“g°oŒ0\b²PcÁÐÒÂÈ%#DôwµïbN÷¾Ô½¿ù–´ýû(«6ÑÖ#ÆÓ¬NøŒ˜“YkœÀºjÇ¥\\yãû¨f#oL¤IGDÂñ¤ð…å$qB=ϱœ€ZüBo–H“U&\vqS®øtíÜNÉìÓNÀ.˜‚¶ÏÂœZvh\ràÊòèl¹†4æýŠ7µc9¨7C&I§°ŠÆ=ß* É\fÕ0Gí,61ô7ÑþB½è^ö0øà"
Looks like the server returns gzip encoded response. So make sure that you have set the AutomaticDecompression property when making your HTTP request: public string GetJson(string url) { var request = (HttpWebRequest)WebRequest.Create(url); request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate"; request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; using (var response = (HttpWebResponse)request.GetResponse()) using (var stream = response.GetResponseStream()) using (var reader = new StreamReader(stream)) { string strResponse = reader.ReadToEnd(); return strResponse; } } Also please get rid of those application/json content types. You are making a GET request which doesn't have a body - you are not sending any JSON. Also get rid of the contentType switch in your jQuery AJAX request (same reason).
Pass fancytree data as JSON data
I want to pass the data from a fancytree to a generic handler so that I can save it for future use. If I use this code: function SaveTree() { var tree = $('#TopTree').fancytree("getTree"); $.ajax({ cache: false, url: "SaveTree.ashx", data: { 'treeData': tree }, contentType: "application/json; charset=utf-8" }); } Then I get the following error from jquery.js: JavaScript runtime error: Argument not optional I have also tried: var tree = $('#TopTree').fancytree("getTree").rootNode.children; This gives the same error. I understand it is because 'tree' is not JSON. How can I convert the data to a JSON object? EDIT: If I use this code: function SaveTree() { var data = []; var tree = $('#TopTree').fancytree("getTree").rootNode.children; for (var i = 0; i < tree.length; i++) { data.push(tree[i].title) } data = JSON.parse(JSON.stringify(data)) $.ajax({ cache: false, url: "SaveTree.ashx", data: { 'treeData': data }, contentType: "application/json; charset=utf-8" }); } I can get it to accomplish what I need, but is there not a built-in function for this in fancytree?
Okay, I don't really know a lot about FancyTree; however, I did some investigation and found this page http://wwwendt.de/tech/fancytree/demo/sample-api.html. Try the tree.ToDict() option to see if that is what you're looking for. This is the source code. // Convert the whole tree into an dictionary var tree = $("#tree").fancytree("getTree"); var d = tree.toDict(true); alert(JSON.stringify(d));
Json Data Not mapped in the backend service
I have a Spring MVC web application and I have the following web service. #RequestMapping(value = "/newBill", method = RequestMethod.POST) public #ResponseBody ModelMap acceptNewBill(#ModelAttribute ("Bill") Bill newBill ){ Bill bill = new Bill(); bill.setTableName(newBill.getTableName()); bill.setRoom(newBill.getRoom()); bill.setCovers(newBill.getCovers()); ModelMap model = new ModelMap(); model.put("status", true); return model; } The following Script performs the front end functions. $('.done').click(function(){ var jsonObject = createJSON(".newBill"); jQuery.ajax({ url: "/newBill", type: "POST", data: {bill: JSON.stringify(jsonObject) }, dataType: "json", beforeSend: function(x) { if (x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } }, success: function(result) { alert('sadgsd'); } }); }); function createJSON(elementToConvert) { jsonObj = []; $( elementToConvert + " input").each(function() { var id = $(this).attr("class"); var email = $(this).val(); item = {} item [id] = email; jsonObj.push(item); }); return jsonObj; } The above createJSON function go through a provided html element and puts the values into an object! The click function performs the POST and the Post contains the following data. bill [{"tableName":"326432"},{"room":"3462346"},{"covers":"3426234"}] Now when I debug and check the service, the data which goes from the front end doesn't get mapped in the parameter. I checked whether the variable names are the same as the POST. They are the same! but the values doesn't get mapped! Can any one please help me with this issue. Update : I changed the service method to GET and passed a value as a URL variable. Then it got mapped in the service param. The problem is in the POST.
Instead of using #ModelAttribute in your controller use #RequestBody: public #ResponseBody ModelMap acceptNewBill(#RequestBody Bill newBill) { On the ajax call, set the content type to application/json and stringify the whole object instead of just the array: jQuery.ajax({ url: "/newBill", type: "POST", data: JSON.stringify({bill: jsonObject}), dataType: "application/json", beforeSend: function(x) { if (x && x.overrideMimeType) { x.overrideMimeType("application/j-son;charset=UTF-8"); } }, success: function(result) { alert('sadgsd'); } });