How can i remove escape sequences to format into proper json? - 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!
Related
Tableau: import JSON data from simple REST call
I have a REST API (served by an external server) replying JSON formatted data. From what I read from Tableau doc, there's available: - WebDataConnector but you have to add a JS overload on your webpages, not very suitable for REST APIs - importing JSON data from file, but doesn't answer my issue Isn't there a simple way to integrate JSON data requested via REST call ?
You can use WDC, you are wrong that its not suitable for REST API. So you basically need to create 2 functions for getting fields and data for your datasets from API: myConnector.getSchema = function (schemaCallback) { $.ajax({ url: apiurl + JSON.parse(tableau.connectionData)['diggerID'] + "/sessions/last/data/one", type: "GET", headers: { 'Authorization': 'Token ' + JSON.parse(tableau.connectionData)['apiKey'] }, success: function(response){ var flatten = objectFlatten(response) var columns = [] for (var key in flatten) { var id = key.replace(/[^A-Za-z0-9_]+/g, '') columns.push({ id: id, alias: key, dataType: tableauType(flatten[key]) }) } var table = { id: "digger_" + JSON.parse(tableau.connectionData)['diggerID'], alias: tableau.connectionName, columns: columns } schemaCallback([table]); }, error: function (xhr, ajaxOptions, thrownError) { tableau.abortWithError("Unable to get data. Make sure you used proper API key and you have at least one session for selected digger with dataset."); } }); }; myConnector.getData = function (table, doneCallback) { $.ajax({ url: apiurl + JSON.parse(tableau.connectionData)['diggerID'] + "/sessions/last/data", type: "GET", headers: { 'Authorization': 'Token ' + JSON.parse(tableau.connectionData)['apiKey'] }, success: function(response){ var data = [] for (var i=0; i < response.length; i++) { var flatten = objectFlatten(response[i]) var rec = {} for (var key in flatten) { var id = key.replace(/[^A-Za-z0-9_]+/g, '') rec[id] = flatten[key] } data.push(rec) } table.appendRows(data); doneCallback(); }, error: function (xhr, ajaxOptions, thrownError) { tableau.abortWithError("Unable to get data. Make sure you used proper API key and you have at least one session for selected digger with dataset."); } }); }; For complete code you can check out for source code on github: https://github.com/Diggernaut/diggernaut-wdc
Extjs Ajax request sending json object to ASP.NET MVC webapp
I'm trying to send a json object (extjs client ) to asp.net server side application: This is the request (with sample data but same logic): var datiOrdine = []; for (i = 0; i < elencoChk.length; i++) { datiOrdine.push ({ x: arr[i].value1, // string y: arr[i].value2, // string z: arr[i].value3, // string k: arr[i].value4, // string (dd/MM/yyyy) l: arr[i].value5, // double }); } Ext.Ajax.request({ url: '/RAMMVC/RDA/UpdateRDA', params: { array: Ext.JSON.encode(datiOrdine) }, headers: { 'Content-Type': 'application/json; charset=utf-8' }, method: "POST", success: function (response) {}, failure: function (response) {} }); The json object: [ { "x":"GRT02", "y":"0215000050", "z":"0001", "k":"30/01/2015", "l":1413.5 } ] And this is the method I declare on server side web application: public ActionResult UpdateRDA(?) { } How can I declare the param(?) on UpdateRDA method to receive correctly the json object? Missing any annotations? If I declare public ActionResult UpdateRDA(string array) { } I get Invalid Json Primitives exception. Programming languages: client UI: extjs 4.1 server: asp.net MVC 3, net framework 4.0
I was able to get your example working with a few small changes on similar setup (MVC3, ExtJS 4.2). For your Ajax request you don't need 'method' as 'post' will be the default when parameters are present. Also, I am not familiar with the 'headers' property, I only know of 'defaultHeaders'. In any case you should not have the headers property set. Here's what I used as a test case: var datiOrdine = []; for (i = 0; i < 10; i++) { datiOrdine.push({ x: "GRT02", // string y: "0215000050", // string z: "0001", // string k: "30/01/2015", // string (dd/MM/yyyy) l: 1413.5, // double }); } Ext.Ajax.request({ url: '/myserver/Controller/Method', params: { array: Ext.JSON.encode(datiOrdine) }, success: function (response) { alert('yes'); }, failure: function (response) { } }); The server side method: public ActionResult Test(string array) { var test = array; return Content(""); }
public ActionResult UpdateRDA(FormCollection collection)` { // TODO }
extract data from 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.
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'); } });
sending multiple models via json in mvc3
Could not find exact matches for the question (some similar posts found) .. How can multiple models be send via JSON to MVC3 controller e.g having the following parameters: public JsonResult Add(Project pr, List<Modules> mod) { } following technique was tried but did not work function AddModules() { var pname = $("#ProjectName").val(); var data = new Array(); var modules = new Array(); $("#ModuleTable tr").each(function () { var row = { "ModuleName": $(this).find(".moduleName").val(), "ModuleDesc": $(this).find(".moduleDesc").val(), "ModuleSize": $(this).find(".moduleSize").val(), "StartDate": $(this).find(".startDate").val(), "ModuleId": "", "ProjectName": pname } modules.push(row); }); var project = { "ProjectName": $("#ProjectName").val(), "ProjectDescription" : $("#ProjectDescription").val(), "StartDate" : $("#ProjectStartDate").val(), "ModuleName" : modules } data.push(project); $.ajax({ url: "AddProject", data: JSON.stringify(data), type: "post", contentType: "application/json; charset = utf-8", dataType: "json", success: function (status) { alert(status); } }); } The project class also contains a List type of Module class.
You are sending a string of JSON back to the server, so you have a type difference. Try something like this instead: Client Side var myFunction = function(){ var projectName = $("#ProjectName").val(); var projectDescription = $("#ProjectDescription").val(); $.post("[URL TO YOUR CONTROLLER]",{pName : projectName, pDescription: projectDescription},function(response){ alert(response); }); }; Server Side public ActionResult MyActionResult(FormCollection fc) { var projectName = fc["pName"]; var projectDescription = fc["pDescription"]; var result = projectName + " hase been posted!"; return Content(result); } Good luck!