【问题标题】:json arrays of object with quotaions mark带有引号的对象的json数组
【发布时间】:2017-07-06 13:50:29
【问题描述】:

我正在尝试向我的 apiController 发送一个 json 对象:

myJson 我这样动态构造的对象:

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 元素上的引号,这会导致服务器端出现反序列化问题。

请你帮我删除引号?

提前谢谢你。

【问题讨论】:

    标签: angularjs arrays json quotation-marks


    【解决方案1】:

    据我所知,问题是这样的

    course.studentList = $scope.results;
    

    因为这一行正在将字符串添加到您的 JSON 对象中,因为 ng-model 为您提供字符串而不是对象,您在 JSON 数组中添加的内容。

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

    【讨论】:

    • 嗨 Wasif,我已经尝试过了,但它给了我这个错误:SyntaxError: Unexpected token , in JSON at position 112
    • 是的,由于您的 JSON 无效,因此会出错。你能告诉我这是 ng-model {"studfirstname":"2","studlastname":"","studAge":"21"} 的值吗?如果您尝试将其添加到变量中以解析它,则这是无效的 JSON。它应该像在 JSON 对象中被解析的引号转义示例: var v="{\"studfirstname\":\"2\",\"studlastname\":\"\",\"studAge\":\" 21\"}";那么你可以这样做:JSON.parse(v);
    • 正是我想做的,但我不知道如何逃避那些引号!
    • 为此,您需要构建一个正则表达式。好简单。如果您愿意,我也可以帮助您使用正则表达式。
    • 我找到了解决方案,请看我的回答。非常感谢您的帮助。
    【解决方案2】:

    我找到了一个简单的解决方案:

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

    这解决了我的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      • 2014-01-18
      相关资源
      最近更新 更多