0% found this document useful (0 votes)
96 views43 pages

NGT Journal

Write a MongoDB query to create a replica of an existing database by: 1) Assigning a replica set name in the configuration file and restarting MongoDB 2) Initiating the replica set from the mongo shell 3) Adding secondary members to the replica set by specifying their hostnames 4) Verifying the replica set status shows all members An arbiter member can also be added to break election ties if there is an even number of members. The arbiter stores no data and has less performance requirements than full members.

Uploaded by

arbaz khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views43 pages

NGT Journal

Write a MongoDB query to create a replica of an existing database by: 1) Assigning a replica set name in the configuration file and restarting MongoDB 2) Initiating the replica set from the mongo shell 3) Adding secondary members to the replica set by specifying their hostnames 4) Verifying the replica set status shows all members An arbiter member can also be added to break election ties if there is an even number of members. The arbiter stores no data and has less performance requirements than full members.

Uploaded by

arbaz khan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Practical Faculty

Program Title Date


No Sign

1 MongoDB Basics

a Write a MongoDB query to create and drop database.

Write a MongoDB query to create, display and drop


b
collection

Write a MongoDB query to insert, query, update and


c
delete a document.

2 Simple Queries with MongoDB

3 Implementing Aggregation

Write a MongoDB query to use sum, avg, min and max


a
expression.

Write a MongoDB query to use push and addToSet


b
expression.

c Write a MongoDB query to use first and last expression.

4 Replication, Backup and Restore

Write a MongoDB query to create Replica of existing


a
database.

Write a MongoDB query to create a backup of existing


b
database

Write a MongoDB query to restore database from the


c
backup.

5 Java and MongoDB

Connecting Java with MongoDB and inserting, retrieving,


a
updating and deleting.

6 PHP and MongoDB

Page 1
Connecting PHP with MongoDB and inserting, retrieving,
a
updating and deleting.

7 Python and MongoDB

Connecting Python with MongoDB and inserting,


a
retrieving, updating and deleting.

8 Programs on Basic jQuery

a jQuery Basic, jQuery Events

b jQuery Selectors, jQuery Hide and Show effects

c jQuery fading effects, jQuery Sliding effects

9 jQuery Advanced

a jQuery Animation effects, jQuery Chaining

b jQuery Callback, jQuery Get and Set Contents

c jQuery Callback, jQuery Get and Set Contents

10 JSON

a Creating JSON

b Parsing JSON

c Persisting JSON

Page 2
Practical no. - 1

MongoDB Basics:-
a) Write a MongoDB query to create and drop database.

 Creating database
Test>use TYIT_UBS

//use command is use to create database TYIT_UBS if not available if


available it is use to switch into TYIT_UBS database and following prompt
will be display.

TYIT_UBS>

 Dropping database
TYIT_UBS> db.dropDatabase() //it will drop TYIT_UBS Database.
Output :-

b) Write a MongoDB query to create, display and drop collection

TYIT_UBS>db.createCollection(“students”)
//it will create new collection with name students.

TYIT_UBS>db.students.insertOne({"rollno":1,"name":"sunita"})
//it will insert a record in a collection.

TYIT_UBS>db.students.find().pretty()
//it will display all records from collection students.

TYIT_UBS>db.students.drop()

Page 3
//it will drop students collection from the TYIT_UBS Database.

Output :-

c) Write a MongoDB query to insert, query, update and delete a document.

TYIT_UBS>db.students.insertMany([{name:"Patrick", age:30, gpa:1.5},


{name:"Sandy", age:27, gpa:4.0},{name:"Gary", age:18, gpa:2.5}])
//above command will insert 3 records

TYIT_UBS>db.students.updateOne({name:”Gary”},{$set:{age:20}})
//it will update a record Gary with age = 20

TYIT_UBS>db.students.deleteOne({name:”Gary”})
//it will delete a record name = Gary
Output :-

Page 4
Practical no. - 2
Simple queries in MongoDB
a) Write a query in mongodb to create database <<TYIT>> and create collection
<<students>> with following fields and insert five records as given below:

{111,”Ajit”,25,2.3,true},{112,”Amit”,24,4.0,false},{114,”Saif”,27,4.3,true},{116,”Shubham”,
23,2.6,false}
1. Roll no
2. Name
3. Age
4. Gpa
5. FullTime

Output :-

Page 5
b) Write a query to increase gpa of all the students by 1.0 for those who
are fullTime and their gpa>3.0

TYIT>db.students.updateMany({fullTime:true,gpa:{$gt:3.0}},{$inc:{gpa:1.0}})
// This function is used to update multiple documents in the "students"
collection.
And those gpa is greater than >3.0 will increase by gpa 1.0

Output :-

Page 6
c) Write query to sort the document based on the age of the students in
decreasing order.

TYIT>db.students.find().sort({age:-1})

Output :-

Page 7
Page
8
Practical no. - 3
Implementing Aggregation
a) Write a MongoDB query to use sum, avg, min and max expression.

TYIT> db.students.find().pretty()

TYIT>db.students.aggregate([{$group:{_id:null,Minage:{$min:”$age”}}}])
[{_id:null, Minage:23}]
db.students.aggregate([{$group:{_id:null,Minage:{$max:”$age”}}}])
[{_id:null, Minage:27}]
db.students.aggregate([{$group:{_id:null,Minage:{$avg:”$age”}}}])
[{_id:null, Minage:24.75}]
db.students.aggregate([{$group:{_id:null,Minage:{$sum:”$age”}}}])
[{_id:null, Minage:99}]

Page
9
b) Write a MongoDB query to use push and addToSet expression.

TYIT> db.students.updateOne({name:”Ajit”},{$push:{subjects:”NEXT GENERATION


TECHNOLOGY}})
//$push to add a new subjects to the “subjects”array.
//This will add the “NEXT GENERATION TECHNOLOGY” to the “subjects” array of the
specified user.

TYIT> db.students.updateOne({name:”Ajit”},{$addToSet:{subjects:”INTERNET OF
THINGS”}})
//$addToSet to add a new subjects to the subjects array while ensuring uniqueness.
//This will add the "INTERNET OF THINGS" to the "subjects" array of the specified user if it does not already

Page
10
c) Write a MongoDB query to use first and last expression.

Syntax:

First
{$first:<expression>}
Last
{$last:<expression>}

Source Code:
use minimum
db.createCollection(“Sales”)
db.Sales.insert({“_id”:1,”item”:”abc”,”price”:10,”quantity”:2,”date”:ISODate(“2014-01-
01T08:00:00Z”)}
db.Sales.insert({“_id”:2,”item”:”jkl”,”price”:20,”quantity”:1,”date”:ISODate(“2014-02-
03T09:00:00Z”)}
db.Sales.insert({“_id”:3,”item”:”xyz”,”price”:5,”quantity”:5,”date”:ISODate(“2014-02-
03T09:00:00Z”)}
db.Sales.insert({“_id”4,”item”:”abc”,”price”:10,”quantity”:10,”date”:ISODate(“2014-02-
15T08:00:00Z”)}
db.Sales.insert({“_id”:5,”item”:”xyz”,”price”:5,”quantity”:10,”date”:ISODate(“2014-02-
15T09:00:00Z”)}
db.sales.aggregate([{$group:{_id:”$item”,Date:{$first:”$date”}}}])
db.sales.aggregate([{$group:{_id:”$item”,Date:{$last:”$date”}}}])

Output:

Page
11
Practical no-4

Replication, Backup and Restore


a) Write a mongoDb query to create replica of existing database.
1) Create Replica Set

 MongoDB must successfully be running on the primary server instance. The


standalone instance of MongoDB can become a replica set member by assigning by
replica set name in the MongoDB configuration file.
 To create a replica set called “rs0”, add the following line to/etc/mongod conf.
replSet=rs0
 MongoDB will need to be restarted for the change to take affect.
Sudo/etc/init.d/mongod restart
 Use the mongo shell to connect once the service is running again.
mongo
 Initiate the replica set from within the mongo shell.
rs.initiate()
 The initial replica set configuration can be verified using rs.conf().

rs.conf()
{
“_id”:”rs0”,
“version”:1,
“members”:{
{
“_id”:0,
“host”:”mongodb01.yourdomain.com:27017”
}
]
}

 At this stage, the mongo shell prompt should also indicate the replica name and
replica member role. For example:
Rs0:PRIMARY>
 The replica set is now created but more member must be added to achieve
redundancy and increased data availability.

Add Secondary Members

 The secondary MongoDB server instances must be successfully running MongoDB


and accessible by the other members.
 The configuration file on the secondary members must reflect the same replica set
name as the primary member. Add the following line to the/etc/mongod.conf on all
the secondary members.
replSet=rs0
 Restart the MongoDB service.
Sudo/etc/init.d/mongod restart
 The secondary members can now be added from the mongo shell on the
primary server using rs.add().
rs():PRIMARY>rs.add(“mongodb02.yourdomain.com”)
rs():PRIMARY>rs.add(“mongodb03.yourdomain.com”)

Page
12
 The rs.status() command can be used to verify the status of the replica set:
rs.status()
Add an Arbiter
 An arbiter is an optional member of a replica set which stores no data. Instead it is
available to break election ties in a situation where there is an even number of
MongoDB members.
 An arbiter member does not require the same performance capabilities of a full
MongoDB server, but it must reside on a separate server instance. Never configure
an arbiter on an existing replica set member.
 To add an arbiter, first install MongoDB on a server instance accessible by the other
replica set members and add the replica set name to/etc/mongod.conf.
replSet=rs0
 Unneccessary data can be reduced on the arbiter server by adding the following files
to/etc/mongod.conf.
journal.enabled=false
smallFiles=true
preallocDataFiles=false
 Now long into the primary replica set member and launch the mongo shell.
mongo
 The arbiter can be added with the following command:
rs.addArb(“arbiter01.yourdomain.com:27017”)

b) Write a mongoDB query to create a backup of existing database


1)Backup a wholedatabase
Mongodump-d devdb-o mongoBackups
devdb is the name of the database and mongoBackups is the directory in which 1 want to
dump the database.

2) Backup a Single Collection


Mongodump –d devdb-o mongoBackups—collection vehicles
devdb is the name of the database and mongoBackups is the directory in which I want to
dump the database and vehicles is the name of the collection which I want to backup.

c) Write a mongoDb query to Restore database from the backup


1) Restore Whole Database
Mongorestore –d devdb mongoBackups/devdb

devdb is the name of the database into which we will restore data and mongoBackups is the
directory in which dumped the database devdb.

Page
13
Practical no. 5
Java with MongoDB
Inserting Data

Source Code:
package javamongodb;
import com.mongodb.DB;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.Iterator;
import org.bson.Document;
public static void main(String[]args){
try{
MongoClient mongoclient=new
MongoClient(“localhost”,27017);
MongoDatabase db=mongoclient.getDatabase(“JAVA”);
System.out.println(“Connected to Database”);
Document document=new Document();
document.append(“_id”,”4010”);
document.append(“name”,”arman”);
document.append(“age”,”20”);
document.append(“city”,”Chennai”);
document.append(“_id”,”4011”);
document.append(“name”,”irfan”);
document.append(“age”,”20”);
document.append(“city”,”mumbai”);
document.append(“_id”,”4012”);
document.append(“name”,”rizwan”);
document.append(“age”,”21”);
document.append(“city”,”Delhi”);
document.append(“_id”,”4013”);
document.append(“name”,”kamru”);
document.append(“age”,”22”);
document.append(“city”,”Delhi”);
document.append(“_id”,”4014”);
document.append(“name”,”sohail”);
document.append(“age”,”21”);
document.append(“city”,”Banglore”);
db.getCollection(“text”).insertOne(document);
System.out.println(“Data Inserted Successfully!!!”);
FindIterable iterDoc=db.getCollection(“text”).find();
int I=1l
iterator it=iterDoc.iterator();
while(it.hasNext()){
System.out.println(it.next());
I++;
}
}catch(Exception e)

Page
14
{
System.out.println(e);
}
}

Output:-

Retreive:-
Source Code:-
package javamongodb;
import com.mongodb.DB;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.Iterator;
import org.bson.Document;
public static void main(String[]args){
try{
MongoClient mongoclient=newMongoClient(“localhost”,27017);
MongoDatabase
db=mongoclient.getDatabase(“JAVA”);
System.out.println(“Connected to Database”);
FindIterable iterDoc=db.getCollection(“text”).find();
int I=1;
Iterator it=iterDoc.iterator();

Page
15
while(it.hasNext()){
System.out.println(it.next());
I++;
}
}catch(Exception e)
{
System.out.println(e);
}
}
}

Output:-

Update:-
Source Code:

package javamongodb;
import com.mongodb.DB;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.Iterator;
import org.bson.Document;
public class update
{
public static void main(String[]args){
try{
MongoClient mongoclient=newMongoClient(“localhost”,27017);
MongoDatabase

Page
16
db=mongoclient.getDatabase(“mydatabase”);
System.out.println(“Connected to Database”);
db.getCollection(“example”).updateOne(Filters.eq(“_id”,”102”),Updates.set(“city”,”vishakat
nam”));
System.out.println(“Data Updated Successfully !!!”);
FindIterable iterDoc=db.getCollection(“example”).find();
int I=1;
Iterator it=iterDoc.iterator();
while(it.hasNext()){
System.out.println(it.next());
i++;
}
}catch(Exception e)
{
System.out.println(e);
}
}

Before update:-

Page
17
After update:

Page
18
Delete
Source Code:
package javamongodb;
import com.mongodb.DB;

Page
19
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.Iterator;
import org.bson.Document;
public class delete{
public static void main(String[]args){
try{
MongoClient mongoclient=newMongoClient(“localhost”,27017);
MongoDatabase
db=mongoclient.getDatabase(“mydatabase”);
System.out.println(“Connected to Database”);
db.getCollection(“example”).deleteOne(Filters.eq(“_id”,”4009”)
);
FindIterable iterDoc=db.getCollection(“example”).find();
int I=1;
Iterator it=iterDoc.iterator();
while(it.hasNext()){
System.out.println(it.next());
i++;
}
}catch(Exception e)
{
System.out.println(e);
}
}
}

Output:-
Before delete:-

Page
20
After delete:-

Page
21
Practical no -6

PHP & MongoDB


Connecting PHP with MongoDB and inserting, retrieving, updating and deleting.

Setting up the environment by installing mongodb php driver:-

Connecting to MongoDB:-

CRUD Operation
Inserting Data:

Retrieving Data:-

Page
22
Updating Data:-
$filter = ['email' => 'john@example.com'];
$update = ['$set' => ['name' => 'Jane Doe']];

$result = $collection->updateOne($filter, $update);


echo "Matched " . $result->getMatchedCount() . " document(s) and modified " . $result-
>getModifiedCount() . " document(s).";

Deleting Data:-

Conclusion:-
We successfully connected PHP with MongoDB and performed CRUD operations.
MongoDB’s flexibility and the official mongodb PHP driver made it relatively easy to work
with NoSQL database in my PHP applications. This combination is a powerful choice for web
developers who need to manage and manipulate data in a flexible and scalable manner.

Page
23
Practical no. 7
Python and MongoDB
a) Connecting Python with MongoDB and inserting, retrieving, updating and deleting

Inserting & Retrieving


Source code:

from pymongo import


MongoClient
#Creating a pymongo client
client=MongoClient(‘localhost’,27017)
#Getting the database
#instance
db=client[‘mydatabase’]
#Creating a collection
coll=db[‘example’]
#inserting document into a collection
data=[{“_id”:”101”,”name”:”Ram”,”age”:26”,”city”:”Hyderabad”},{“_id”:”102”,”name”:”Rahi
m”,”age”:27”,”city”:”Bangalore”},{“_id”:”103”,”name”:”Robert”,”age”:28”,”city”:”Mumbai”}]
res=coll.insert_many(data)
print(“Data inserted…..”)
print(res.inserted_ids)
#Retrieving the first record using the find_one() method
print(“First record of the collection:”)
print(coll.find_one())
#Retrieving a record with is 103 using
#thefind_one()
method print(“Record whose id is 103:”)
print(coll.find_one({“_id”:”103”}))

Output:-

Update:-
Update One
Source code:
From pymongo import MongoClient
#Creating a pymongo client
client=MongoClient(‘localhost’,27017)
#Getting the database instance
db=client[‘myDBase’]
#Creating a collection

Page
24
coll=db[‘MYExample2’]
#Inserting document into a collection
data=[{“_id”:”301”,”name”:”Ram”,”age”:26”,”city”:”Hyderabad”),{“_id”:”302”,”name”:”Rahi
m”,”age”:27”,”city”:”Bangalore”),{“_id”:”303”,”name”:”Robert”,”age”:28”,”city”:”Mumbai”)]
res=coll.insert_many(data)
print(“Data inserted…..”)
#Retrieving all the records using the find() method
print(“Documents in the collection:”)
for doc1 in coll.find():
print(doc1)
coll.update_many({},{“$set”:{“city”:”Vishakhapatnam”}})
#Retrieving all the records using the find() method
print(“Documents in the collection after update operation:”)
for doc2 in coll.find():
print(doc2)

Output:-

Delete
Delete One
Source code:
from pymongo import MongoClient
#Creating a pymongo client
client=MongoClient(‘localhost’,27017)
#Getting the database instance
db=client[‘mydatabase’]
#Creating a collection
coll=db[‘Myexample’]
#inserting document into a collection
data=[{“_id”:”5001”,”name”:”Ram”,”age”:26”,”city”:”Hyderabad”},{“_id”:”5002”,”name”:”R
ahim”,”age”:27”,”city”:”Bangalore”},{“_id”:”5003”,”name”:”Robert”,”age”:28”,”city”:”Mum
bai”},{“_id”:”5004”,”name”:”Romeo”,”age”:25”,”city”:”Pune”},{“_id”:”5005”,”name”:”Sarmi
sta”,”age”:23”,”city”:”Delhi”},{“_id”:”5006”,”name”:”Rasajna”,”age”:26”,”city”:”Chennai”}]
res=coll.insert_many(data)
print(“Data inserted…..”)
print(res.inserted_ids)
#Deleting one document
coll.delete_one({“_id”:”5006”})
#Retrieving all the records using the find() method
print(“Documents in the collection after update operation:”)

Page
25
for doc2 in coll.find():
print(doc2)

Output:-

Delete Many
Source code:
from pymongo import
MongoClient
client=MongoClient(‘localhost’,27017)
#Getting the database instance
db=client[‘sampleDB’]
#Creating a collection
db[‘example4’]
#Inserting document into
data=[{“_id”:”1001”,”name”:”Ram”,”age”:26”,”city”:”Hyderabad”},{“_id”:”1002”,”name”:”R
ahim”,”age”:27”,”city”:”Bangalore”},{“_id”:”1003”,”name”:”Robert”,”age”:28”,”city”:”Mum
bai”},{“_id”:”1004”,”name”:”Romeo”,”age”:25”,”city”:”Pune”},{“_id”:”1005”,”name”:”Sarmi
sta”,”age”:23”,”city”:”Delhi”},{“_id”:”1006”,”name”:”Rasajna”,”age”:26”,”city”:”Chennai”}]
res=coll.insert_many(data)
print(“Data inserted…..”)
#Deleting multiple documents
coll.delete_many({“age”:{“$gt”:”26”}})
#Retrieving all the records using the find() method
print(“Documents in the collection after update operation:”)
for doc2 in coll.find()
print(doc2)

Output:-

Page
26
Practical no. 8

Programs on Basic JQuery


jQuery Basic
Code:-
<html>
<head>
<title>The jQuery Example</title>
</head>
<body>
<p>This is 1st paragraph</p>
<p>This is 2nd paragraph</p>
<p>This is 3rd paragraph</p>
</body>
</html>

Output:-

This is 1st paragraph.

This is 2nd paragraph.

This is 3rd paragraph

jQuery Events
Click Event:
Code:-
<html>
<head>
<script type=”text/javascript” src=”https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/
jquery.min.js”></script>
<script type-”text/javascript”>
$(document).ready(function(){
$(‘div’).bind(‘click’,function(event)(alert(‘Event type is’+event.type); alert(‘Target:’+event.
Target.innerHTML);
});
});
</script>
.div{margin:10px;padding:12px; border:2px solid#666; width:60px;}
</style>
</head>
<body>
<p>Click on any square below to see the result;</p>
<div class=”div” style = “background-color:blue;”>ONE</div>
<div class=”div” style = “background-color:green;”>TWO</div>
<div class=”div” style = “background-color:red;”>THREE</div>
</body>
</html>

Output:-

Page
27
DoubleClick Event
Source Code:-

Page
28
Output:-

Mouseleave
Source Code:-

Page
29
Output:-

b) jQuery Selectors
Code:-

Page
30
Output:-

ID Selector:-
Source Code:-

Page
31
Output:-

jQuery Hide and Show Effect:-


Source Code:-

Output:-

Page
32
jQuery Fading Effect:
Source Code:-

Output:-

jQuery Sliding Effect:-


Source Code:-

Page
33
Output:-

Page
34
Practical No. 9

jQuery Advanced
jQuery Animation
Source Code

Output:-

jQuery Chaining-
Source Code:-
<html>
<head>
<script
src=”https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“button”).click(function(){
$(“#p1).css(“color”,”red”).slideUp(2000).slideDown(2000);
});
});
</script>;
</head>
<body>
<p id=”p1”>jQuery is fun!!</p>
<button>Click Me</button>
</body>

Page
35
</html>

Output:-

jQuery Callback
Source Code:-
<html>
<head>
<script type=”text/javascript”
src=””https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”>
</script>
$(document).ready(function(){
$(“button”).click(function(){$(“p”).hide(“slow”,function(){alert(“The paragraph is hidden
now”);
});
});
});
</script>
</head>
<body>
<button>Hide </button>
<p>This is a paragraph with little content</p>
</body>
</html>
Output:-

Page
36
jQuery Get Content
Source Code:-
<html>
<head>
<script type=”text/javascript”
src=””https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”>
</script>
$(document).ready(function(){
$(“button”).click(function(){alert(“Value :”+$(“#test”).val());
});
});
</script>
</head>
<body>
<p>Name:<Input type=”text” id=”test” value=”Mickey Mouse”></p>
<button>Show value </button>
</body>
</html>

Output:-

Set Content
Source Code:-

Page
37
Output:-

jQuery Insert Content

Page
38
Source Code:-
<script>
$(document).ready(function(){
$(“#btn1”).click(function(){
$(“p”).append(“<b>Appended text </b>.”);
});
$(“#btn2).click(function(){
$(“ol”).append(“<li>Appended item</li>”);
});
}0;
</script>
<body>
<p>This is a ;paragraph.</p>
<p>This is another paragraph.</p>
<ol>
<li>List item1</li>
<li>List item2</li>
<li>List item3</li>
<ol>
<button id=”btn1”>Append text</button>
<button id=”btn2”>Append list items</button>
</body>

Output:-

Page
39
jQuery Remove Content and attribute
Source Code:-
<head>
<script>
$(document).ready(fucntion(){
$(“button”).click(function(){
$(“div1”).remove();
});
});
</script>
</head>
<body>
<div id=”div1” style=”height:100px;width:300px;border:1px solid black;background-color:
Yellow;”>This is some text in the div.

Page
40
<p>This is another paragraph in the div.</p>
</div>
<br>
<button>Remove div element</button>
</body>

Output:-

Page
41
Practical No. 10

JSON
Creating JSON
Source Code:-
<html>
<body>
<p>Access a JSON object using dot notation:</p>
<p id=”demo”></p>
<script>var myObj, x;
myObj={“name”:”John”,”age”:30,”car”:null}; x=myObj.name;
document.getElementById(“demo”).innerHTML=x;
</script>
</body>
</html>

Output:-

Modify JSON
Source Code:-
<body>
<p>How to modify values in a JSON object.</p>
<p id=”demo”></p>
<script> var myObj, 1, x=””; myObj={
“name”:”John”,
“age”:30,
“cars”:{
“car1”:”Ford”,
“car2”:”BMW”,
“car3”:”Fiat”
}
}
myObj.cars.car2=”Mercedes”; for(I in myObj.cars) {x+=myObj.cars[I]+”<br>”;
}
Document.getElementById(“demo”).innerHTML=x;
</script>
</body>

Output:-

Page
42
Parsing JSON
Source Code:-
<body>
<h2>Create Object from JSON String</h2>
<p id=”demo”></p>
<script.
Var txt=’{“name”:”John”,”age”:30,”city”:”New York”)’
Var obj=JSON.parse(txt);
Document.getElementById(“demo”).innerHTML=obj.name+”,”+obj.age+”,”+obj.city;
</script>
</body>

Output:-

Page
43

You might also like