-2

I am trying to send an json object to my apiController :

myJson Object that I construct dynamicaly like this :

var course= new Object();
course.info= $scope.info;
course.studentList = [];
course.studentList = $scope.results; 

$scope.results is an array that I get from my view :

<select  ng-model="results[$index]" >
    <option value=""></option>
    <option ng-repeat="r in myList" value={{r}}>{{r.studlastname}}</option>
</select>

what I expect :

{
"course": {
     "courseName":"yyy",
     "courseDesc":"xxxx",
     "prof":"prof1"
},
"studentList" :[
    {"studfirstname":"2","studlastname":"","studAge":"21"},
    {"studfirstname":"4","studlastname":"","studAge":"40"},
    {"studfirstname":"6","studlastname":"","studAge":"60"}
]
}

what I have :

{
"course": {
     "courseName":"yyy",
     "courseDesc":"xxxx",
     "prof":"prof1"
},
"studentList" :[
    "{"studfirstname":"2","studlastname":"","studAge":"21"}",
    "{"studfirstname":"4","studlastname":"","studAge":"40"}",
    "{"studfirstname":"6","studlastname":"","studAge":"60"}"
]
}

notice the quotations on every studentList element, this is causing deserialization problem on server side.

please can you help me to remove the quotations ?

thank you in advance.

LLai
  • 13,128
  • 3
  • 41
  • 45

2 Answers2

0

From what I can see, Problem here is this

course.studentList = $scope.results;

because this line is adding string into your JSON Object as ng-model gives you string instead of object what you are adding in JSON Array.

course.studentList = JSON.parse($scope.results);
Wasif Khan
  • 956
  • 7
  • 25
  • Hi Wasif, I already tried this but it give me this error : **SyntaxError: Unexpected token , in JSON at position 112** – anonymouslyGeek Jul 06 '17 at 14:07
  • yes, it is giving error as your JSON is not valid. can you tell me that this is the value of ng-model {"studfirstname":"2","studlastname":"","studAge":"21"} right? this is invalid JSON if u try to add it in variable to parse it. it should be like quote escaped to be parsed in JSON Object Example: var v="{\"studfirstname\":\"2\",\"studlastname\":\"\",\"studAge\":\"21\"}"; then u can do something like this: JSON.parse(v); – Wasif Khan Jul 06 '17 at 14:18
  • exactly what I want to do, but i can't figure out how to escape those quotes! – anonymouslyGeek Jul 06 '17 at 14:23
  • for this, you need to build a regex. very easy. I can help you with regex too if you wish to. – Wasif Khan Jul 06 '17 at 14:28
  • I found a solution, pls take a look to my answer. thank you so much for your help. – anonymouslyGeek Jul 06 '17 at 14:31
0

I found an easy solution :

let objectArray = $scope.results.map((each)=>{return JSON.parse(each)});
course.studentsList = objectArray;

this solved my problem.