在AngularJs,以下是工作 -
$scope.product= {items:[{itemname:'apple',itemdesc:'fruit'}]}
但我想从下面的JSON字符串得到$scope.product
-
var strJson = "{items:[{itemname:'apple',itemdesc:'fruit'}]}";
$scope.product=strJson;
不工作。我所有的是一个JSON字符串,我需要分配到$scope.product
。我已使用JSON.parse()
和JSON.toJson()
,但它们不起作用。 我不知道我做错了什么
下面是我的确切代码:
$http.get('/getItems').success(function(data) {
var jsondata="{\items\:";
jsondata+=JSON.stringify(data);
jsondata+="}";
jsondata=jsondata.replace(/"itemname"/g, 'itemname');
jsondata=jsondata.replace(/"itemdesc"/g, 'itemdesc');
// WORKING CODE
$scope.product = {items:[{itemname:"apple",itemdesc:"fruit"}]};
// NOT WORKING CODE
var jsonObj = jsondata;
$scope.product = jsonObj;
});
我刚编辑答案。希望downvoter将审查这一 –
Myexact问题是这样的:$ http.get( '/ getItems')成功(功能(数据){ \t VAR jsondata = “{\项目\”。 \t jsondata + = JSON.stringify (数据); \t jsondata + = “}”; \t jsondata = jsondata.replace(/ “ITEMNAME”/ G 'ITEMNAME'); \t jsondata = jsondata。替换(/“itemdesc”/ g,'itemdesc'); \t \t // \t工作代码 \t $ scope.product = {项目:[{ITEMNAME: “苹果”,itemdesc: “水果”}]}; \t \t \t \t \t // \t不工作CODE \t变种jsonObj = jsondata; \t $ scope.product = jsonObj; }); –