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.
There is no way to parse a JSON file asynchronously.
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)
}
})
Top comments (4)
The upcoming async interface for
fs
cleans this up a little further:Why would you want to do that, though? Wrapping the operation into a promise may delay its execution, but when it's executed, it will run in the main thread, like everything else, and nothing else will run until it finishes parsing the json string.
Good point Victor, I think I meant "out of the box" with the parse method, but you're right! I will incorporate your suggestion in the article!
Awesome Article Flavio, I am also newbie in NodeJS and JSON. Sometime, I use jsonformatter.org to format and validate JSON data.