Use Node.js to parse JSON

How to parse JSON from a string, and how to read a JSON file in Node.js

if you haveJSON formatThe data is part of the string, the best way to parse it is to useJSON.parseThe method has become part of the JavaScript standard since ECMAScript 5, byV8, A powerful JavaScript engineNode.js.

example:

const data = '{ "name": "Flavio", "age": 35 }'
try {
  const user = JSON.parse(data)
} catch(err) {
  console.error(err)
}

noteJSON.parseIt is synchronous, so the larger the JSON file, the longer the execution of your program will be blocked before the JSON is parsed.

You can wrap the JSON incommitted toAnd setTimeout call to ensure that the parsing is performed 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, you must first read it.

A very simple way is to userequire():

const data = require('./file.json')

Because you used.jsonexpand,require()Smart enough to understand this, and indatapurpose.

One warning is that file reading is synchronous. In addition, the result of the require() call will be cached, so if it is called again due to updating the file, the new content will not be obtained until the program exits.

This feature is provided for application configuration using JSON files, which is a very effective use case.

You can also read the file manually usingfs.readFileSync:

const fs = require('fs')
const fileContents = fs.readFileSync('./file.json', 'utf8')

try { const data = JSON.parse(fileContents) } catch(err) { console.error(err) }

This will read the file synchronously.

You can also use asynchronous read filefs.readFile, This is the best choice. In this case, the file content will be provided as a callback, and inside the callback you can process 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 mine for freeNode.js manual


More node tutorials: