SlideShare una empresa de Scribd logo
1 de 17
Unit-2
Working with JSON
What is JSON?
J ava S cript O bject N otation, or JSON, is a lightweight data format
that has become the defacto standard for the web. JSON can be
represented as either a list of values, e.g. an Array, or a hash of
properties and values, e.g. an Object.
Array, Object
[ a, m, y ]
{ name : value }
// a JSON array
["one", "two", "three"]
// a JSON object
{
"one": 1, // name : “Mukesh”
"two": 2,
"three": 3
}
Format of Node.js Object: JSON-
object
• Create an Object of student:
var student =
{
Name: "Amit",
Branch:"BCA",
City: "kathmandu",
Mobile: "99946730"
};
Encoding and Decoding
JavaScript provides 2 methods for encoding data structures to json and
encoding json back to JavaScript objects and arrays. They are both
available on the JSON object that is available in the global scope.
JSON.stringify takes a JavaScript object or array and returns a serialized
string in the JSON format.
const data = {
name: 'John Doe',
age: 32,
title: 'Vice President of JavaScript'
};
const jsonStr = JSON.stringify(data);
console.log(jsonStr);
// prints '{"name":"John Doe","age":32,"title":"Vice President of
JavaScript"}'
JSON.parse takes a JSON string and decodes it to a
JavaScript data structure.
const jsonStr =
'{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}';
const data = JSON.parse(jsonStr);
console.log(data.title);
// prints 'Vice President of JavaScript'
What is valid JSON?
There are a few rules to remember when dealing with data in JSON
format. There are several gotchas that can produce invalid JSON as well.
• Empty objects and arrays are okay
• Strings can contain any unicode character, this includes object properties
• null is a valid JSON value on it's own
• All object properties should always be double quoted
• Object property values must be one of the following: String, Number,
Boolean, Object, Array, null
• Number values must be in decimal format, no octal or hex
representations
• Trailing commas on arrays are not allowed
These are all examples of valid JSON.
{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}
["one", "two", "three"]
// nesting valid values is okay
{"names": ["John Doe", "Jane Doe"] }
[ { "name": "John Doe"}, {"name": "Jane Doe"} ]
{} // empty hash
[] // empty list
null
{ "key": "uFDD0" } // unicode escape codes
These are all examples of bad JSON formatting.
{ name: "John Doe", 'age': 32 } // name and age should be in double
quotes
[32, 64, 128, 0xFFF] // hex numbers are not allowed
{ "name": "John Doe", "age": undefined } // undefined is an invalid
value
// functions and dates are not allowed
{ "name": "John Doe",
"birthday": new Date('Fri, 26 Jan 2019 07:13:10 GMT'),
"getName": function() {
return this.name;
}}
Calling JSON.parse with an invalid JSON string will result in a
SyntaxError being thrown. If you are not sure of the validity of your
JSON data, you can anticipate errors by wrapping the call in a try/catch
block.
Notice that the only complex values allowed in JSON are objects and
arrays. Functions, dates and other types are excluded. This may not
seem to make sense at first. But remember that JSON is a data format,
not a format for transferring complex JavaScript objects along with their
functionality.
Example-1
const book = {
title : “Node.js Book",
author : "Basarat Ali Syed"
}
const bookJSON = JSON.stringify(book)
console.log(book)
console.log(bookJSON)
Example-2
const book =
{
title : "Narinder Modi",
author : "xyz"
}
const bookJSON = JSON.stringify(book)
console.log(book.title)
console.log(bookJSON.title)
Example-3
const book =
{
title : "Narinder Modi",
author : "xyz"
}
const bookJSON = JSON.stringify(book)
console.log(book.title)
console.log(bookJSON.title)
const bookObj = JSON.parse(bookJSON)
console.log(bookObj.title)
Example-4
const fs = require("fs")
const book = {
title : "Narinder Modi",
author : "xyz"
}
const bookJSON = JSON.stringify(book)
console.log(book.title)
console.log(bookJSON.title)
const bookObj = JSON.parse(bookJSON)
console.log(bookObj.title)
fs.writeFileSync("myjson.json",bookJSON)
Example-5
const fs = require("fs")
//const book = {
// title : "Narinder Modi",
// author : "xyz"
//}
//const bookJSON = JSON.stringify(book)
//console.log(book.title)
//console.log(bookJSON.title)
//const bookObj = JSON.parse(bookJSON)
const dataBuffer = fs.readFileSync("myjson.json")
//console.log(dataBuffer)
console.log(dataBuffer.toString())
Example-6
const fs = require("fs")
//const book = {
// title : "Narinder Modi",
// author : "xyz"
//}
//const bookJSON = JSON.stringify(book)
//console.log(book.title)
//console.log(bookJSON.title)
//const bookObj = JSON.parse(bookJSON)
const dataBuffer = fs.readFileSync("myjson.json")
//console.log(dataBuffer)
const dataJSON = dataBuffer.toString()
const bookObj = JSON.parse(dataJSON)
console.log(bookObj)
Example-7
const fs = require("fs")
//const book = {
// title : "Narinder Modi",
// author : "xyz"
//}
//const bookJSON = JSON.stringify(book)
//console.log(book.title)
//console.log(bookJSON.title)
//const bookObj = JSON.parse(bookJSON)
const dataBuffer = fs.readFileSync("myjson.json")
//console.log(dataBuffer)
const dataJSON = dataBuffer.toString()
const bookObj = JSON.parse(dataJSON)
console.log(bookObj.title)

Más contenido relacionado

Similar a Working with JSON.pptx

json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
AmitSharma397241
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)
Faysal Shaarani (MBA)
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
HemaSenthil5
 

Similar a Working with JSON.pptx (20)

Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
Hands on JSON
Hands on JSONHands on JSON
Hands on JSON
 
Store non-structured data in JSON column types and enhancements of JSON
Store non-structured data in JSON column types and enhancements of JSONStore non-structured data in JSON column types and enhancements of JSON
Store non-structured data in JSON column types and enhancements of JSON
 
java script json
java script jsonjava script json
java script json
 
json.ppt download for free for college project
json.ppt download for free for college projectjson.ppt download for free for college project
json.ppt download for free for college project
 
BITM3730Week8.pptx
BITM3730Week8.pptxBITM3730Week8.pptx
BITM3730Week8.pptx
 
Unit-2 JSON.pdf
Unit-2 JSON.pdfUnit-2 JSON.pdf
Unit-2 JSON.pdf
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptx
 
JSON(JavaScript Object Notation) Presentation transcript
JSON(JavaScript Object Notation) Presentation transcriptJSON(JavaScript Object Notation) Presentation transcript
JSON(JavaScript Object Notation) Presentation transcript
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)JSON Data Parsing in Snowflake (By Faysal Shaarani)
JSON Data Parsing in Snowflake (By Faysal Shaarani)
 
JSON - JavaScript Object Notation
JSON - JavaScript Object NotationJSON - JavaScript Object Notation
JSON - JavaScript Object Notation
 
JSON.pptx
JSON.pptxJSON.pptx
JSON.pptx
 
Json at work overview and ecosystem-v2.0
Json at work   overview and ecosystem-v2.0Json at work   overview and ecosystem-v2.0
Json at work overview and ecosystem-v2.0
 
module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...module 2.pptx for full stack mobile development application on backend applic...
module 2.pptx for full stack mobile development application on backend applic...
 
Json
JsonJson
Json
 
Dealing with JSON files in python with illustrations
Dealing with JSON files in python with illustrationsDealing with JSON files in python with illustrations
Dealing with JSON files in python with illustrations
 
Json demo
Json demoJson demo
Json demo
 
JSON
JSONJSON
JSON
 

Más de Lovely Professional University

web_server_browser.ppt
web_server_browser.pptweb_server_browser.ppt
web_server_browser.ppt
Lovely Professional University
 
Web Server.pptx
Web Server.pptxWeb Server.pptx
Number System.pptx
Number System.pptxNumber System.pptx
Number System.pptx
Lovely Professional University
 
Programming Language.ppt
Programming Language.pptProgramming Language.ppt
Programming Language.ppt
Lovely Professional University
 
Information System.pptx
Information System.pptxInformation System.pptx
Information System.pptx
Lovely Professional University
 
Applications of Computer Science in Pharmacy-1.pptx
Applications of Computer Science in Pharmacy-1.pptxApplications of Computer Science in Pharmacy-1.pptx
Applications of Computer Science in Pharmacy-1.pptx
Lovely Professional University
 
Application of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptxApplication of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptx
Lovely Professional University
 
Requiring your own files.pptx
Requiring your own files.pptxRequiring your own files.pptx
Requiring your own files.pptx
Lovely Professional University
 

Más de Lovely Professional University (20)

The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup language
 
Yargs Module
Yargs ModuleYargs Module
Yargs Module
 
NODEMON Module
NODEMON ModuleNODEMON Module
NODEMON Module
 
Getting Input from User
Getting Input from UserGetting Input from User
Getting Input from User
 
fs Module.pptx
fs Module.pptxfs Module.pptx
fs Module.pptx
 
Transaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptxTransaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptx
 
web_server_browser.ppt
web_server_browser.pptweb_server_browser.ppt
web_server_browser.ppt
 
Web Server.pptx
Web Server.pptxWeb Server.pptx
Web Server.pptx
 
Number System.pptx
Number System.pptxNumber System.pptx
Number System.pptx
 
Programming Language.ppt
Programming Language.pptProgramming Language.ppt
Programming Language.ppt
 
Information System.pptx
Information System.pptxInformation System.pptx
Information System.pptx
 
Applications of Computer Science in Pharmacy-1.pptx
Applications of Computer Science in Pharmacy-1.pptxApplications of Computer Science in Pharmacy-1.pptx
Applications of Computer Science in Pharmacy-1.pptx
 
Application of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptxApplication of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptx
 
Deploying your app.pptx
Deploying your app.pptxDeploying your app.pptx
Deploying your app.pptx
 
Setting up github and ssh keys.ppt
Setting up github and ssh keys.pptSetting up github and ssh keys.ppt
Setting up github and ssh keys.ppt
 
Adding a New Feature and Deploying.ppt
Adding a New Feature and Deploying.pptAdding a New Feature and Deploying.ppt
Adding a New Feature and Deploying.ppt
 
Requiring your own files.pptx
Requiring your own files.pptxRequiring your own files.pptx
Requiring your own files.pptx
 
Unit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptxUnit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptx
 
Yargs Module.pptx
Yargs Module.pptxYargs Module.pptx
Yargs Module.pptx
 
Restarting app with Nodemon.pptx
Restarting app with Nodemon.pptxRestarting app with Nodemon.pptx
Restarting app with Nodemon.pptx
 

Último

Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 

Último (20)

data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptxA CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
A CASE STUDY ON CERAMIC INDUSTRY OF BANGLADESH.pptx
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 

Working with JSON.pptx

  • 2. What is JSON? J ava S cript O bject N otation, or JSON, is a lightweight data format that has become the defacto standard for the web. JSON can be represented as either a list of values, e.g. an Array, or a hash of properties and values, e.g. an Object. Array, Object [ a, m, y ] { name : value }
  • 3. // a JSON array ["one", "two", "three"] // a JSON object { "one": 1, // name : “Mukesh” "two": 2, "three": 3 } Format of Node.js Object: JSON- object • Create an Object of student: var student = { Name: "Amit", Branch:"BCA", City: "kathmandu", Mobile: "99946730" };
  • 4. Encoding and Decoding JavaScript provides 2 methods for encoding data structures to json and encoding json back to JavaScript objects and arrays. They are both available on the JSON object that is available in the global scope. JSON.stringify takes a JavaScript object or array and returns a serialized string in the JSON format.
  • 5. const data = { name: 'John Doe', age: 32, title: 'Vice President of JavaScript' }; const jsonStr = JSON.stringify(data); console.log(jsonStr); // prints '{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}'
  • 6. JSON.parse takes a JSON string and decodes it to a JavaScript data structure. const jsonStr = '{"name":"John Doe","age":32,"title":"Vice President of JavaScript"}'; const data = JSON.parse(jsonStr); console.log(data.title); // prints 'Vice President of JavaScript'
  • 7. What is valid JSON? There are a few rules to remember when dealing with data in JSON format. There are several gotchas that can produce invalid JSON as well. • Empty objects and arrays are okay • Strings can contain any unicode character, this includes object properties • null is a valid JSON value on it's own • All object properties should always be double quoted • Object property values must be one of the following: String, Number, Boolean, Object, Array, null • Number values must be in decimal format, no octal or hex representations • Trailing commas on arrays are not allowed
  • 8. These are all examples of valid JSON. {"name":"John Doe","age":32,"title":"Vice President of JavaScript"} ["one", "two", "three"] // nesting valid values is okay {"names": ["John Doe", "Jane Doe"] } [ { "name": "John Doe"}, {"name": "Jane Doe"} ] {} // empty hash [] // empty list null { "key": "uFDD0" } // unicode escape codes
  • 9. These are all examples of bad JSON formatting. { name: "John Doe", 'age': 32 } // name and age should be in double quotes [32, 64, 128, 0xFFF] // hex numbers are not allowed { "name": "John Doe", "age": undefined } // undefined is an invalid value // functions and dates are not allowed { "name": "John Doe", "birthday": new Date('Fri, 26 Jan 2019 07:13:10 GMT'), "getName": function() { return this.name; }}
  • 10. Calling JSON.parse with an invalid JSON string will result in a SyntaxError being thrown. If you are not sure of the validity of your JSON data, you can anticipate errors by wrapping the call in a try/catch block. Notice that the only complex values allowed in JSON are objects and arrays. Functions, dates and other types are excluded. This may not seem to make sense at first. But remember that JSON is a data format, not a format for transferring complex JavaScript objects along with their functionality.
  • 11. Example-1 const book = { title : “Node.js Book", author : "Basarat Ali Syed" } const bookJSON = JSON.stringify(book) console.log(book) console.log(bookJSON)
  • 12. Example-2 const book = { title : "Narinder Modi", author : "xyz" } const bookJSON = JSON.stringify(book) console.log(book.title) console.log(bookJSON.title)
  • 13. Example-3 const book = { title : "Narinder Modi", author : "xyz" } const bookJSON = JSON.stringify(book) console.log(book.title) console.log(bookJSON.title) const bookObj = JSON.parse(bookJSON) console.log(bookObj.title)
  • 14. Example-4 const fs = require("fs") const book = { title : "Narinder Modi", author : "xyz" } const bookJSON = JSON.stringify(book) console.log(book.title) console.log(bookJSON.title) const bookObj = JSON.parse(bookJSON) console.log(bookObj.title) fs.writeFileSync("myjson.json",bookJSON)
  • 15. Example-5 const fs = require("fs") //const book = { // title : "Narinder Modi", // author : "xyz" //} //const bookJSON = JSON.stringify(book) //console.log(book.title) //console.log(bookJSON.title) //const bookObj = JSON.parse(bookJSON) const dataBuffer = fs.readFileSync("myjson.json") //console.log(dataBuffer) console.log(dataBuffer.toString())
  • 16. Example-6 const fs = require("fs") //const book = { // title : "Narinder Modi", // author : "xyz" //} //const bookJSON = JSON.stringify(book) //console.log(book.title) //console.log(bookJSON.title) //const bookObj = JSON.parse(bookJSON) const dataBuffer = fs.readFileSync("myjson.json") //console.log(dataBuffer) const dataJSON = dataBuffer.toString() const bookObj = JSON.parse(dataJSON) console.log(bookObj)
  • 17. Example-7 const fs = require("fs") //const book = { // title : "Narinder Modi", // author : "xyz" //} //const bookJSON = JSON.stringify(book) //console.log(book.title) //console.log(bookJSON.title) //const bookObj = JSON.parse(bookJSON) const dataBuffer = fs.readFileSync("myjson.json") //console.log(dataBuffer) const dataJSON = dataBuffer.toString() const bookObj = JSON.parse(dataJSON) console.log(bookObj.title)