AngularJS的angular.fromJson()方法可以把一个Json字符串中解析成一个对象,或对象数组:
<!DOCTYPE html> <html ng-app="App"> <head> <meta charset="UTF-8"> <title></title> <script src="https://www.jb51.net/js/angular.js"></script> <script type="text/javascript"> angular.module("App", []) .controller("parseController", function($scope) { $scope.parse = function() { var json = '{"name":"liSi", "password":"321"}'; var jsonArr = '[{"name":"zhangSan", "password":"123"},{"name":"liSi", "password":"321"}]'; var obj = angular.fromJson(json); console.log(obj.name); var objArr = angular.fromJson(jsonArr); console.log(objArr[0].name); console.log(objArr[1].password); } }); </script> </head> <body> <div ng-controller="parseController"> <button ng-click="parse()">点击我!</button> </div> </body> </html>
控制台打印的结果如下:
liSi zhangSan 321
相应地,能够从Json到对象,就能够从对象到Json:
var obj = { name:"liSi", password:"321" } var str = angular.toJson(obj, true); console.log(str);
打印结果如下:
{ "name": "liSi", "password": "321" }
PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《AngularJS指令操作技巧总结》、《AngularJS入门与进阶教程》及《AngularJS MVC架构总结》