2017-07-06 50 views
-2

我想一個JSON對象發送到我的apiController:JSON陣列,quotaions標記

myJson對象,我構建dynamicaly這樣的:

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

$ scope.results是一個數組我從我的觀點得到:

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

我的期望:

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

我有:

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

通知每個studentList元素上的報價,這是在服務器端反序列化造成的問題。

請你能幫我刪除報價嗎?

謝謝你提前。

回答

0

從我所看到的,這裏的問題是這樣

course.studentList = $scope.results; 

因爲該行字符串添加到您的JSON對象爲NG-模型給出的,而不是對象,你的字符串,你在JSON陣列所添加的。

course.studentList = JSON.parse($scope.results); 
+0

嗨Wasif, 我已經嘗試過這一點,但它給我這個錯誤: **語法錯誤:意外的標記,在JSON位置112處** – anonymouslyGeek

+0

是的,它是給錯誤作爲你的JSON是無效的。你能告訴我這是ng-model的價值嗎? {「studfirstname」:「2」,「studlastname」:「」,「studAge」:「21」}對不對? 這是無效的JSON,如果你嘗試將它添加到變量來解析它。它應該像引用轉義,在JSON對象中解析 示例: var v =「{\」studfirstname \「:\」2 \「,\」studlastname \「:\」\「,\」studAge \「: \ 「21 \」}「; 然後你可以做這樣的事情: JSON.parse(v); –

+0

正是我想要做的,但我無法弄清楚如何逃避這些引號! – anonymouslyGeek

0

我發現了一個簡單的解決方案:

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

這個解決我的問題。