If you have JSON data as part of a string, the best way to parse it is by using the JSON.parse
method that’s part of the JavaScript standard since ECMAScript 5, and it’s provided by V8, the JavaScript engine that powers Node.js.
Example:
const data = '{ "name": "Flavio", "age": 35 }'
try {
const user = JSON.parse(data)
} catch(err) {
console.error(err)
}
Note that JSON.parse
is synchronous, so the more the JSON file is big, the more time your program execution will be blocked until the JSON is finished parsing.
You can process the JSON asynchronously by wrapping it in a promise and a setTimeout call, which makes sure parsing takes place in the next iteration of the event loop:
const parseJsonAsync = (jsonString) => {
return new Promise(resolve => {
setTimeout(() => {
resolve(JSON.parse(jsonString))
})
})
}
const data = '{ "name": "Flavio", "age": 35 }'
parseJsonAsync(data).then(jsonData => console.log(jsonData))
If your JSON is in a file instead, you first have to read it.
A very simple way to do so is to use require()
:
const data = require('./file.json')
Since you used the .json
extension, require()
is smart enough to understand that, and parse the JSON in the data
object.
One caveat is that file reading is synchronous. Plus, the result of the require() call is cached, so if you call it again because you updated the file, you won’t get the new contents until the program exits.
This feature was provided to use a JSON file for the app configuration, and it’s a perfectly valid use case.
You can also read the file manually, using fs.readFileSync
:
const fs = require('fs')
const fileContents = fs.readFileSync('./file.json', 'utf8')
try {
const data = JSON.parse(fileContents)
} catch(err) {
console.error(err)
}
This reads the file synchronously.
You can also read the file asynchronously using fs.readFile
, and this is the best option. In this case, the file content is provided as a callback, and inside the callback you can process the JSON:
const fs = require('fs')
fs.readFile('/path/to/file.json', 'utf8', (err, fileContents) => {
if (err) {
console.error(err)
return
}
try {
const data = JSON.parse(fileContents)
} catch(err) {
console.error(err)
}
})
Download my free Node.js Handbook
More node tutorials:
- An introduction to the npm package manager
- Introduction to Node.js
- HTTP requests using Axios
- Where to host a Node.js app
- Interact with the Google Analytics API using Node.js
- The npx Node Package Runner
- The package.json guide
- Where does npm install the packages?
- How to update Node.js
- How to use or execute a package installed using npm
- The package-lock.json file
- Semantic Versioning using npm
- Should you commit the node_modules folder to Git?
- Update all the Node dependencies to their latest version
- Parsing JSON with Node.js
- Find the installed version of an npm package
- Node.js Streams
- Install an older version of an npm package
- Get the current folder in Node
- How to log an object in Node
- Expose functionality from a Node file using exports
- Differences between Node and the Browser
- Make an HTTP POST request using Node
- Get HTTP request body data using Node
- Node Buffers
- A brief history of Node.js
- How to install Node.js
- How much JavaScript do you need to know to use Node?
- How to use the Node.js REPL
- Node, accept arguments from the command line
- Output to the command line using Node
- Accept input from the command line in Node
- Uninstalling npm packages with `npm uninstall`
- npm global or local packages
- npm dependencies and devDependencies
- The Node.js Event Loop
- Understanding process.nextTick()
- Understanding setImmediate()
- The Node Event emitter
- Build an HTTP Server
- Making HTTP requests with Node
- The Node fs module
- HTTP requests in Node using Axios
- Reading files with Node
- Node File Paths
- Writing files with Node
- Node file stats
- Working with file descriptors in Node
- Working with folders in Node
- The Node path module
- The Node http module
- Using WebSockets with Node.js
- The basics of working with MySQL and Node
- Error handling in Node.js
- The Pug Guide
- How to read environment variables from Node.js
- How to exit from a Node.js program
- The Node os module
- The Node events module
- Node, the difference between development and production
- How to check if a file exists in Node.js
- How to create an empty file in Node.js
- How to remove a file with Node.js
- How to get the last updated date of a file using Node.js
- How to determine if a date is today in JavaScript
- How to write a JSON object to file in Node.js
- Why should you use Node.js in your next project?
- Run a web server from any folder
- How to use MongoDB with Node.js
- Use the Chrome DevTools to debug a Node.js app
- What is pnpm?
- The Node.js Runtime v8 options list
- How to fix the "Missing write access" error when using npm
- How to enable ES Modules in Node.js
- How to spawn a child process with Node.js
- How to get both parsed body and raw body in Express
- How to handle file uploads in Node.js
- What are peer dependencies in a Node module?
- How to write a CSV file with Node.js
- How to read a CSV file with Node.js
- The Node Core Modules
- Incrementing multiple folders numbers at once using Node.js
- How to print a canvas to a data URL
- How to create and save an image with Node.js and Canvas
- How to download an image using Node.js
- How to mass rename files in Node.js
- How to get the names of all the files in a folder in Node
- How to use promises and await with Node.js callback-based functions
- How to test an npm package locally
- How to check the current Node.js version at runtime
- How to use Sequelize to interact with PostgreSQL
- Serve an HTML page using Node.js
- How to solve the `util.pump is not a function` error in Node.js