SlideShare una empresa de Scribd logo
1 de 25
Descargar para leer sin conexión
Unit-2
Working with JSON
What is JSON?
Java Script Object Notation, 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 pitfall 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)
How to read and write JSON file using
Node.js ?
Method 1: Using require method: The simplest method to read a JSON
file is to require it in a node.js file using require() method.
• const data = require('path/to/file/filename’);
• Example: Create a users.json file in the same directory where index.js
file present. Add following data to the JSON file.
• users.json file:
[
{
"name": "John",
"age": 21,
"language": ["JavaScript", "PHP", "Python"]
},
{
"name": "Smith",
"age": 25,
"language": ["PHP", "Go", "JavaScript"]
}
]
Now, add the following code to your index.js file.
const users = require("./users");
console.log(users);
Now, run the file using the command:
node index.js
• Method 2: Using the fs module: We can also use node.js fs module to
read a file. The fs module returns a file content in string format so we
need to convert it into JSON format by using JSON.parse() in-built
method.
• Add the following code into your index.js file:
• index.js file:
const fs = require("fs");
// Read users.json file
fs.readFile("users.json", function(err, data) {
// Check for errors
if (err) throw err;
// Converting to JSON
const users = JSON.parse(data);
console.log(users); // Print users
});
Writing to a JSON file: We can write data into a JSON file by
using the node.js fs module. We can use writeFile method to
write data into a file.
• Syntax: fs.writeFile("filename", data, callback);
Example: We will add a new user to the existing JSON file, we
have created in the previous example. This task will be
completed in three steps:
• Read the file using one of the above methods.
• Add the data using .push() method.
• Write the new data to the file using JSON.stringify() method
to convert data into string.
const fs = require("fs"); // STEP 1: Reading JSON file
const users = require("./users"); // Defining new user
let user = {
name: "New User",
age: 30,
language: ["PHP", "Go", "JavaScript"]
};
// STEP 2: Adding new data to users object
users.push(user);
// STEP 3: Writing to a file
fs.writeFile("users.json", JSON.stringify(users), err => {
// Checking for errors
if (err) throw err;
console.log("Done writing"); // Success
});

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

javascript objects
javascript objectsjavascript objects
javascript objects
 
Nodejs buffers
Nodejs buffersNodejs buffers
Nodejs buffers
 
PostgreSQL
PostgreSQLPostgreSQL
PostgreSQL
 
Php array
Php arrayPhp array
Php array
 
Nestjs MasterClass Slides
Nestjs MasterClass SlidesNestjs MasterClass Slides
Nestjs MasterClass Slides
 
Json
JsonJson
Json
 
Packages in java
Packages in javaPackages in java
Packages in java
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
Js ppt
Js pptJs ppt
Js ppt
 
React JS - A quick introduction tutorial
React JS - A quick introduction tutorialReact JS - A quick introduction tutorial
React JS - A quick introduction tutorial
 
Introduction to JSON
Introduction to JSONIntroduction to JSON
Introduction to JSON
 
Json
JsonJson
Json
 
JavaScript - Chapter 8 - Objects
 JavaScript - Chapter 8 - Objects JavaScript - Chapter 8 - Objects
JavaScript - Chapter 8 - Objects
 
String in java
String in javaString in java
String in java
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Full Stack Web Development.pptx
Full Stack Web Development.pptxFull Stack Web Development.pptx
Full Stack Web Development.pptx
 
php
phpphp
php
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
 

Similar a JSON-Optimized 40-char title

JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptxdyumna2
 
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
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesSanjeev Kumar Jaiswal
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)Skillwise Group
 
BITM3730Week8.pptx
BITM3730Week8.pptxBITM3730Week8.pptx
BITM3730Week8.pptxMattMarino13
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problemstitanlambda
 
Unit-2 JSON.pdf
Unit-2 JSON.pdfUnit-2 JSON.pdf
Unit-2 JSON.pdfhskznx
 
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 illustrationsKiran Kumaraswamy
 

Similar a JSON-Optimized 40-char title (20)

Working with JSON.pptx
Working with JSON.pptxWorking with JSON.pptx
Working with JSON.pptx
 
Json
JsonJson
Json
 
JSON & AJAX.pptx
JSON & AJAX.pptxJSON & AJAX.pptx
JSON & AJAX.pptx
 
Intro to JSON
Intro to JSONIntro to JSON
Intro to JSON
 
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...
 
Basics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examplesBasics of JSON (JavaScript Object Notation) with examples
Basics of JSON (JavaScript Object Notation) with examples
 
Json
JsonJson
Json
 
Intro to JSON
Intro to JSONIntro to JSON
Intro to JSON
 
JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)JSON-(JavaScript Object Notation)
JSON-(JavaScript Object Notation)
 
CSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptxCSV JSON and XML files in Python.pptx
CSV JSON and XML files in Python.pptx
 
Hands on JSON
Hands on JSONHands on JSON
Hands on JSON
 
BITM3730Week8.pptx
BITM3730Week8.pptxBITM3730Week8.pptx
BITM3730Week8.pptx
 
JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2JavaScript Lessons 2023 V2
JavaScript Lessons 2023 V2
 
JSON Fuzzing: New approach to old problems
JSON Fuzzing: New  approach to old problemsJSON Fuzzing: New  approach to old problems
JSON Fuzzing: New approach to old problems
 
Json tutorial, a beguiner guide
Json tutorial, a beguiner guideJson tutorial, a beguiner guide
Json tutorial, a beguiner guide
 
Unit-2 JSON.pdf
Unit-2 JSON.pdfUnit-2 JSON.pdf
Unit-2 JSON.pdf
 
An introduction to json
An introduction to jsonAn introduction to json
An introduction to json
 
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
 
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
 
Mule: JSON to Object
Mule: JSON to ObjectMule: JSON to Object
Mule: JSON to Object
 

Más de Lovely Professional University

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 languageLovely 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

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024TopCSSGallery
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructureitnewsafrica
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesBernd Ruecker
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxfnnc6jmgwh
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesManik S Magar
 

Último (20)

Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024Top 10 Hubspot Development Companies in 2024
Top 10 Hubspot Development Companies in 2024
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical InfrastructureVarsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
Varsha Sewlal- Cyber Attacks on Critical Critical Infrastructure
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
QCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architecturesQCon London: Mastering long-running processes in modern architectures
QCon London: Mastering long-running processes in modern architectures
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptxGenerative AI - Gitex v1Generative AI - Gitex v1.pptx
Generative AI - Gitex v1Generative AI - Gitex v1.pptx
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotesMuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
MuleSoft Online Meetup Group - B2B Crash Course: Release SparkNotes
 

JSON-Optimized 40-char title

  • 2. What is JSON? Java Script Object Notation, 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 pitfall 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)
  • 18. How to read and write JSON file using Node.js ? Method 1: Using require method: The simplest method to read a JSON file is to require it in a node.js file using require() method. • const data = require('path/to/file/filename’); • Example: Create a users.json file in the same directory where index.js file present. Add following data to the JSON file. • users.json file:
  • 19. [ { "name": "John", "age": 21, "language": ["JavaScript", "PHP", "Python"] }, { "name": "Smith", "age": 25, "language": ["PHP", "Go", "JavaScript"] } ]
  • 20. Now, add the following code to your index.js file. const users = require("./users"); console.log(users); Now, run the file using the command: node index.js
  • 21. • Method 2: Using the fs module: We can also use node.js fs module to read a file. The fs module returns a file content in string format so we need to convert it into JSON format by using JSON.parse() in-built method. • Add the following code into your index.js file: • index.js file:
  • 22. const fs = require("fs"); // Read users.json file fs.readFile("users.json", function(err, data) { // Check for errors if (err) throw err; // Converting to JSON const users = JSON.parse(data); console.log(users); // Print users });
  • 23. Writing to a JSON file: We can write data into a JSON file by using the node.js fs module. We can use writeFile method to write data into a file. • Syntax: fs.writeFile("filename", data, callback);
  • 24. Example: We will add a new user to the existing JSON file, we have created in the previous example. This task will be completed in three steps: • Read the file using one of the above methods. • Add the data using .push() method. • Write the new data to the file using JSON.stringify() method to convert data into string.
  • 25. const fs = require("fs"); // STEP 1: Reading JSON file const users = require("./users"); // Defining new user let user = { name: "New User", age: 30, language: ["PHP", "Go", "JavaScript"] }; // STEP 2: Adding new data to users object users.push(user); // STEP 3: Writing to a file fs.writeFile("users.json", JSON.stringify(users), err => { // Checking for errors if (err) throw err; console.log("Done writing"); // Success });