AngularJS JSON Serializes and Deserializes
AngularJS support JSON . You can Serializes and Deserializes object from AngularJS inbuilt fucntion.'angular.toJson()' Serializes object from JavaScript object to JSON string.'angular.fromJson()' Deserializes JSON string and returns an JavaScript object.
Example 1 ( JavaScript object to JSON)
Output :
{"person":{"firstname":"Ayan","lastname":"Banerjee"},"address":{"city":"Kolkata","state":"South ,24 Pgs(s)"}}
Example 2 ( JavaScript object to JSON)
Example 1 (JSON to JavaScript object)
AngularJS support JSON . You can Serializes and Deserializes object from AngularJS inbuilt fucntion.'angular.toJson()' Serializes object from JavaScript object to JSON string.'angular.fromJson()' Deserializes JSON string and returns an JavaScript object.
Example 1 ( JavaScript object to JSON)
<!DOCTYPE
>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<script>
var
app = angular.module("myApp",
[]);
app.controller("myController",
function
($scope)
{
$scope.model
=
{
student:
{
firstname:
"Ayan",
lastname:
"Banerjee"
},
address:
{
city:
"Kolkata",
state:
"South
,24 Pgs(s)"
}
};
$scope.jsonData
= angular.toJson($scope.model);
});
</script>
<div
style="background-color:
#F0F0F0; width:
400px;">
<div
ng-app="myApp">
<div
ng-controller="myController"
>
<span>{{jsonData}}</span>
</div>
</div>
</div>
Output :
{"person":{"firstname":"Ayan","lastname":"Banerjee"},"address":{"city":"Kolkata","state":"South ,24 Pgs(s)"}}
Example 2 ( JavaScript object to JSON)
<!DOCTYPE
>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<script>
var
app = angular.module("myApp",
[]);
app.controller("myController",
function
($scope)
{
var
Obj = {};
Obj.weight
= 75;
Obj.height
= 180;
Obj.colors
= {};
Obj.colors.r
= 150;
Obj.colors.g
= 278;
Obj.colors.b
= 300;
$scope.obj
= Obj;
$scope.SerialisedObj
= angular.toJson($scope.obj, true);
});
</script>
<div
style="background-color:
#F0F0F0; width:
400px;">
<div
ng-app="myApp">
<div
ng-controller="myController"
>
<span>{{SerialisedObj}}</span>
</div>
</div>
</div>
Output :
{
"weight": 75,
"height": 180,
"colors": {
"r": 150,
"g": 278,
"b": 300
}
}
Example 1 (JSON to JavaScript object)
<!DOCTYPE
>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<script>
var
app = angular.module("myApp",
[]);
app.controller("myController",
function
($scope)
{
var
json = '{"name":"Ayan","Hobby":{"Reading":["Story","Novel","Short
Story"]}}';
$scope.obj
= angular.fromJson(json);
});
</script>
<div
style="background-color:
#F0F0F0; width:
400px;">
<div
ng-app="myApp">
<div
ng-controller="myController"
>
<span>Name
: {{obj.name}}</span><br/>
<span
ng-repeat="obj
in obj.Hobby.Reading">{{obj}}<br/></span>
</div>
</div>
</div>
Output :
Name : Ayan
StoryNovelShort Story
StoryNovelShort Story
No comments:
Post a Comment