SlideShare a Scribd company logo
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
});

More Related Content

PPT
Wrapper class (130240116056)
PPT
PHP - Introduction to Object Oriented Programming with PHP
PPT
XML Schema
PDF
full stack practical assignment msc cs.pdf
PPT
SQLITE Android
PPTX
jQuery from the very beginning
PPT
Document Object Model
Wrapper class (130240116056)
PHP - Introduction to Object Oriented Programming with PHP
XML Schema
full stack practical assignment msc cs.pdf
SQLITE Android
jQuery from the very beginning
Document Object Model

What's hot (20)

PPT
Spring data presentation
PPT
Introduction To PHP
PDF
Javascript essentials
PPS
Wrapper class
PPTX
Lab #2: Introduction to Javascript
PDF
JavaScript - Chapter 11 - Events
PPT
ADO.NET
PPTX
Form using html and java script validation
PPTX
Strings in c#
PPT
PDF
jQuery for beginners
PDF
Python programming : Strings
PPTX
Java Strings
PPS
String and string buffer
PDF
PPT
JavaScript Arrays
PDF
Constructing SQL queries for AtoM
PPTX
Object oriented programming in python
Spring data presentation
Introduction To PHP
Javascript essentials
Wrapper class
Lab #2: Introduction to Javascript
JavaScript - Chapter 11 - Events
ADO.NET
Form using html and java script validation
Strings in c#
jQuery for beginners
Python programming : Strings
Java Strings
String and string buffer
JavaScript Arrays
Constructing SQL queries for AtoM
Object oriented programming in python
Ad

Similar to Working with JSON (20)

PPTX
Working with JSON.pptx
PPTX
module 2.pptx for full stack mobile development application on backend applic...
PPTX
module node jsbhgnbgtyuikmnbvcfyum2.pptx
PDF
JavaScript Lessons 2023 V2
PDF
Intro to JSON
PPTX
Json training
PDF
CS8651 IP Unit 2 pdf regulation -2017 anna university
PPTX
JSON - (English)
PDF
Unit-2 JSON.pdf
PPT
java script json
PPTX
1 Json Intro and datatype PRESENTATION.pptx
PPTX
unit5_part2.pptx
PPT
Java Script Object Notation (JSON)
PPTX
JSON-(JavaScript Object Notation)
PDF
Json tutorial, a beguiner guide
PPT
J s-o-n-120219575328402-3
PPT
JavaScript Object Notation (JSON)
PPT
OSS BarCamp Mumbai - JSON Presentation and Demo
PDF
Basics of JSON (JavaScript Object Notation) with examples
PDF
Introduction to JSON
Working with JSON.pptx
module 2.pptx for full stack mobile development application on backend applic...
module node jsbhgnbgtyuikmnbvcfyum2.pptx
JavaScript Lessons 2023 V2
Intro to JSON
Json training
CS8651 IP Unit 2 pdf regulation -2017 anna university
JSON - (English)
Unit-2 JSON.pdf
java script json
1 Json Intro and datatype PRESENTATION.pptx
unit5_part2.pptx
Java Script Object Notation (JSON)
JSON-(JavaScript Object Notation)
Json tutorial, a beguiner guide
J s-o-n-120219575328402-3
JavaScript Object Notation (JSON)
OSS BarCamp Mumbai - JSON Presentation and Demo
Basics of JSON (JavaScript Object Notation) with examples
Introduction to JSON
Ad

More from Lovely Professional University (20)

PPTX
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
PPTX
Effort Estimation: Meaning, Problems with Estimation, Basis, Estimation Techn...
PPTX
Project Approach: Intro. Technical Plan, Choice of Process Models: Waterfall,...
PPTX
Programme Management & Project Evaluation
PPTX
Step Wise Project Planning: Project Scope, Objectives, Infrastructure, Charac...
PPTX
Introduction to Software Project Management:
PDF
The HyperText Markup Language or HTML is the standard markup language
PPTX
PPTX
Getting Input from User
PPTX
PPTX
Transaction Processing in DBMS.pptx
PPT
web_server_browser.ppt
PPTX
PPTX
Number System.pptx
PPT
Programming Language.ppt
PPTX
Information System.pptx
PPTX
Applications of Computer Science in Pharmacy-1.pptx
PPTX
Application of Computers in Pharmacy.pptx
PPTX
Deploying your app.pptx
Activity Planning: Objectives, Project Schedule, Network Planning Model. Time...
Effort Estimation: Meaning, Problems with Estimation, Basis, Estimation Techn...
Project Approach: Intro. Technical Plan, Choice of Process Models: Waterfall,...
Programme Management & Project Evaluation
Step Wise Project Planning: Project Scope, Objectives, Infrastructure, Charac...
Introduction to Software Project Management:
The HyperText Markup Language or HTML is the standard markup language
Getting Input from User
Transaction Processing in DBMS.pptx
web_server_browser.ppt
Number System.pptx
Programming Language.ppt
Information System.pptx
Applications of Computer Science in Pharmacy-1.pptx
Application of Computers in Pharmacy.pptx
Deploying your app.pptx

Recently uploaded (20)

PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Big Data Technologies - Introduction.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Encapsulation theory and applications.pdf
PDF
KodekX | Application Modernization Development
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Cloud computing and distributed systems.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Big Data Technologies - Introduction.pptx
MIND Revenue Release Quarter 2 2025 Press Release
20250228 LYD VKU AI Blended-Learning.pptx
Chapter 3 Spatial Domain Image Processing.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Reach Out and Touch Someone: Haptics and Empathic Computing
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Encapsulation theory and applications.pdf
KodekX | Application Modernization Development
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Cloud computing and distributed systems.
Diabetes mellitus diagnosis method based random forest with bat algorithm
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

Working with JSON

  • 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 });