Mubi 6
Mubi 6
PRACTICAL 6
Aim: Write a program to convert JavaScript objects into string or string into object.
PRACTICAL 6.1
Aim: Creating JSON string into Object
Code:
<!DOCTYPE html>
<html lang="en">
<body>
<h2>Creating JSON string into Object</h2>
<p id="demo"></p>
<script>
const txt='{"name":"mubi","age":19,"city":"vadodara"}'
const obj =JSON.parse(txt);
document.getElementById("demo").innerHTML=obj.name+",
"+obj.age;
</script>
</body>
</html>
Output:
Practical 6.1.1
Aim: Convert a string into date object
WITHOUT
Subject: Application of AWT(CA218) 21102069
Code:
<!DOCTYPE html>
<html lang="en">
<body>
<h2>Convert a string into date object</h2>
<p id="demo"></p>
<script>
const text='{"name":"mubi","birth":"2003-10-
03","city":"vadodara"}'
const obj=JSON.parse(text);
document.getElementById("demo").innerHTML=obj.name+","+obj.birth;
</script>
</body>
</html>
Output:
WITH
Code:
<!DOCTYPE html>
<html lang="en">
<body>
<h2>Convert a string into date object</h2>
<p id="demo"></p>
<script>
const text='{"name":"mubi","birth":"2003-10-
03","city":"vadodara"}'
const obj=JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML=obj.name+","+obj.birth;
</script>
Subject: Application of AWT(CA218) 21102069
</body>
</html>
Output:
Practical 6.1.2
Aim: Convert a String into a function
Code:
<!DOCTYPE html>
<html lang="en">
<body>
<h2>Convert a String into a function</h2>
<p id="demo"></p>
<script>
const text='{"name":"mubi","age":"function(){return
19;}","city":"vadodara"}'
const obj =JSON.parse(text);
obj.age=eval("("+obj.age+")");
document.getElementById("demo").innerHTML=obj.name+","+obj.age();
</script>
</body>
</html>
Output:
Subject: Application of AWT(CA218) 21102069
PRACTICAL 6.2
Aim: Create a JavaScript object into String
Code:
<!DOCTYPE html>
<html lang="en">
<body>
<H2>Create a JavaScript object into string</H2>
<p id="demo"></p>
<script>
const obj = {"name":"mubi","age":19,"city":"vadodara"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML=myJSON;
</script>
</body>
</html>
Output:
Subject: Application of AWT(CA218) 21102069
PRACTICAL 6.2.1
Code:
<!DOCTYPE html>
<html lang="en">
<body>
<h2>JSON.stringify() converts date objects into string</h2>
<p id="demo"></p>
<script>
const obj = {name:"mubi",today:new Date(),city:"vadodara"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML=myJSON;
</script>
</body>
</html>
Output:
Subject: Application of AWT(CA218) 21102069
PRACTICAL 6.2.2
Code:
<!DOCTYPE html>
<html lang="en">
<body>
<h2>JSON.stringify() will remove any function from an object</h2>
<p id="demo"></p>
<script>
const obj={name:"mubi",age:function(){return
19;},city:"vadodara"};
const myJSON = JSON.stringify(obj);
document.getElementById("demo").innerHTML=myJSON;
</script>
</body>
</html>
Output: