Read Json Data From Text File in C#

Read/Write JSON Files with Node.js

Photo by Patrick Tomasso on Unsplash

This article is role of our first tutorial serial, Data Brokering with Node.js on Hey Node , the Node.js preparation site from Osio Labs.

iew the video tutorial on Hey Node .

When you desire to shop data betwixt server restarts with Node, JSON files are a simple and convenient selection. Whether you are reading a config file or persisting information for your awarding, Node has some built in utilities that make information technology easy to read and write JSON files.

Using JSON files in your app can be a useful way to persist data. We will expect at a few different methods for working with JSON files.

In this tutorial we volition:

  • Read JSON data from deejay
  • Learn to use fs module to collaborate with the filesystem
  • Persist data to a JSON file
  • Use JSON.parse and JSON.stringify to convert data to and from JSON format

By the end of this tutorial you should be able to work with JSON files using Node'due south built-in fs module.

Goal

Say you have a customer.json file saved to deejay that holds a tape for a customer in your store.

As part of your store app, you want to access the customer's address, and then update the order count after an guild is placed.

In this tutorial, we are going to expect at how to read and write to our customer.json file.

            // customer.json
{
"name": "Mega Corp.",
"order_count": 83,
"address": "Infinity Loop Drive",
}

Work with files with fs

Accessing files in Node is done with the native module fs, which gives y'all functions to watch, read, and write files along with many other tools to work with the filesystem. Because it'south a native module, we tin crave it in our code without installing it. Just call const fs = crave('fs').

The fs module gives united states of america the selection of synchronous or asynchronous versions of many of its functions. The synchronous versions cake execution of other code until they are done accessing the filesystem, reading, or writing data. An async part will run without blocking other code. You can learn more about sync/async behavior here.

This synchronous beliefs tin can be useful in some places, similar at startup when reading a config file earlier any other lawmaking is run, but becomes a big result when used in a webserver where all incoming requests would be blocked while a synchronous file read is running. For this reason, you generally want to utilise the async versions of fs functions in your code. We will focus on async operations, just volition besides show the synchronous equivalent.

To read and write files asynchronously with fs we will use fs.readFile and fs.writeFile.

We also will use the global JSON helper to convert objects to JSON strings, and JSON strings to objects.

Reading a JSON file

The simplest mode to read a JSON file is to crave information technology. Passing require() with the path to a JSON file will synchronously read and parse the data into a JavaScript object.

            const config = require('./config.json')          

But reading JSON files with crave has its downsides. The file will merely be read in one case; requiring information technology again returns the cached data from the first fourth dimension crave was run. This is fine for loading static data on startup (like config data). But for reading a file that changes on disk, like our customer.json might, we demand to manually read the file using the asynchronous fs.readFile.

Reading a file with fs.readFile

To admission the customer'due south accost, we demand to:

  • read the JSON information from the file
  • parse the JSON string into a JavaScript object

To load the data from customer.json file, we will use fs.readFile, passing it the path to our file, an optional encoding type, and a callback to receive the file data.

If the file is successfully read, the contents will be passed to the callback.

            const fs = require('fs')            fs.readFile('./customer.json', 'utf8', (err, jsonString) => {
if (err) {
console.log("File read failed:", err)
return
}
console.log('File information:', jsonString)
})

'./client.json' is the relative path to the the file 'utf8' is an optional parameter for the encoding of the file we are reading, this can be left out
(err, jsonString) => {} is the callback function that runs later the file has been read.

Now we have the contents of the file every bit a JSON string, but we need to plow the cord into an object.

Before nosotros can utilize the data from the callback in our code, we must turn it into an object. JSON.parse takes JSON data equally input and returns a new JavaScript object. Otherwise, nosotros would just take a cord of information with properties we can't admission.

JSON.parse tin can throw exception errors and crash our plan if passed an invalid JSON string. To prevent crashing we wrap JSON.parse in a endeavor catch statement to gracefully catch any errors.

This example shows reading and parsing a JSON file:

            const fs = crave('fs')            fs.readFile('./client.json', 'utf8', (err, jsonString) => {
if (err) {
console.log("Error reading file from disk:", err)
render
}
try {
const customer = JSON.parse(jsonString)
console.log("Customer address is:", customer.address) // => "Client address is: Infinity Loop Drive"
} grab(err) {
panel.log('Error parsing JSON string:', err)
}
})

Using the jsonString from reading customer.json, we create an object, and can access the address property. If JSON.parse throws an fault, nosotros handle it in the take hold of block.

At present nosotros have an object representation of the information in our customer.json file!

Nosotros tin also read the file synchronously using fs.readFileSync. Instead of taking a callback, readFileSync returns the file content afterwards reading the file.

            try {
const jsonString = fs.readFileSync('./customer.json')
const customer = JSON.parse(jsonString)
} catch(err) {
console.log(err)
return
}
panel.log(client.address) // => "Infinity Loop Drive"

We tin can use this cognition to create a reusable helper function to read and parse a JSON file.

Hither nosotros create a part called jsonReader that will read and parse a JSON file for united states of america. It takes the path to the file and a callback to receive the parsed object and any errors. It will catch whatsoever errors thrown past JSON.parse for u.s..

            const fs = require('fs')            function jsonReader(filePath, cb) {
fs.readFile(filePath, (err, fileData) => {
if (err) {
return cb && cb(err)
}
try {
const object = JSON.parse(fileData)
render cb && cb(zippo, object)
} catch(err) {
return cb && cb(err)
}
})
}
jsonReader('./customer.json', (err, client) => {
if (err) {
panel.log(err)
return
}
console.log(customer.accost) // => "Infinity Loop Drive"
})

Writing to a file with fs.writeFile

Writing JSON to the filesystem is similar to reading it. We will use fs.writeFile to asynchronously write data to a newCustomer.json file.

First, to write data to a JSON file, nosotros must create a JSON string of the data with JSON.stringify. This returns a JSON cord representation of a JavaScript object, which can be written to a file. Similar to parsing information into an object when reading a file, we must plough our data into a cord to be able to write it to a file.

So nosotros create a customer object with our data below, and turn it into a string.

            const client = {
name: "Newbie Corp.",
order_count: 0,
address: "Po Box Urban center",
}
const jsonString = JSON.stringify(customer)
panel.log(jsonString)
// => "{"name":"Newbie Co.","address":"Po Box City","order_count":0}"

If you try to write an object to a file without stringifying it, your file will be empty and look similar this:

[object, object]

Once the information is stringified, we can utilize fs.writeFile to create a new customer file. Nosotros laissez passer fs.writeFile the filepath, our customer information to write, and a callback that will exist excecuted after the file is written. If the newCustomer.json file doesn't already exist, information technology will be created; if it does exist, it volition exist overwritten!

Here is an example of writing a JSON file with fs.writeFile :

            const fs = require('fs')            const client = {
name: "Newbie Co.",
order_count: 0,
accost: "Po Box Urban center",
}
const jsonString = JSON.stringify(customer) fs.writeFile('./newCustomer.json', jsonString, err => {
if (err) {
console.log('Fault writing file', err)
} else {
console.log('Successfully wrote file')
}
})

And that's it! Once the callback runs, the file has been written to disk. Note: we are but passed an error object; the filedata we wrote isn't passed to the callback.

We can besides write a file synchronously in the same way using fs.writeFileSync:

            const jsonString = JSON.stringify(customer)            fs.writeFileSync('./newCustomer.json', jsonString)          

Later on your file is finished writing, it will look something like this:

            {"name":"Newbie Co.","address":"Po Box City","order_count":0}          

Stringifying by default puts your data all on a single line. Optionally, y'all tin can make the output file human-readable by passing the number of spaces to indent by to JSON.stringify:

            const jsonString = JSON.stringify(customer, null, ii)          

Above, nosotros told stringify to indent the data with 2 spaces.

Now your output file should look similar this:

            {
"proper noun": "Newbie Co.",
"address": "Po Box Metropolis",
"order_count": 0
}

Updating JSON files

Now that nosotros are able to read and write our client files, we can use them as a unproblematic kind of database. If nosotros want to update the data in the JSON file, nosotros tin read the contents, modify the data, and and so write the new data dorsum to the file:

            jsonReader('./client.json', (err, customer) => {
if (err) {
console.log('Mistake reading file:',err)
return
}
// increment customer guild count by 1
customer.order_count += 1
fs.writeFile('./customer.json', JSON.stringify(customer), (err) => {
if (err) console.log('Mistake writing file:', err)
})
})

Definitely non the nearly efficient database you lot could cull, but working with JSON files like this is a uncomplicated way to persist information in your projection.

Wrapping up

JSON is one of the nearly common types of data you'll work with in Node, and being able to read and write JSON files is very useful. You've learned how to utilise fs.readFile and fs.writeFile to asynchronously work with the filesystem, also as how to parse information to and from JSON format, and catch errors from JSON.parse.

You can use crave to read a JSON file at startup to synchronously parse a JSON file in ane line. And now you tin can apply a simple JSON file as a data shop.

If you want to learn more, you can read upward on what JSON really is, and detect out more near synchronous vs asynchronous lawmaking.

Written by Jon Church and Joe Shindelar

Welcome to Hey Node , the new Node.js training site from Osio Labs.

nasseralowely44.blogspot.com

Source: https://medium.com/@osiolabs/read-write-json-files-with-node-js-92d03cc82824

0 Response to "Read Json Data From Text File in C#"

Отправить комментарий

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel