SirArchibald
SirArchibald

Reputation: 516

How to read and write to local JSON files from React.js?

I have looked at multiple resources for this, however, none seem to be able to answer my question. I have a local JSON file in my React app called items.json. In that file, is a list of objects, which I want to be able to update. I have tried using fs however this apparently doesn't work in React, as I received this error:

Unhandled Rejection (TypeError): fs.readFileSync is not a function

What I am trying to do, is that when the code gets a new item, it looks through the JSON file to see if there is an existing object with a matching values in its name property. If there is, it increments that objects count property by 1, otherwise it creates a new object, and appends it to the list in the JSON file. This is the code that I have written to do that. The logic seems sound (although its not tested) but I can't figure out how to read/write the data.

let raw = fs.readFileSync("../database/items.json");
let itemList = JSON.parse(raw);
let found = false;
for (let item of itemList.averages) {
    if (item.name === this.state.data.item_name) {
        found = true;
        item.count += 1;
    }
}
if (!found) {
    let newItem = {
        name: this.state.data.item_name,
        count: 1,
    }
    itemList.averages.push(newItem);
}
let newRaw = JSON.stringify(itemList);
fs.writeFileSync("../database/items.json", newRaw);

The JSON file:

{
    "averages": [
        {
            "name": "Example",
            "count": 1,
        }
    ]
}

Upvotes: 10

Views: 79641

Answers (3)

Shariati
Shariati

Reputation: 119

reading and writing JSON file to local storage is quite simple with NodeJs, which means a tiny piece of backend API in express would help get this job done.

few piece of code that might help you. Assuming you JSON structure would be such as below;

{
    "name":"arif",
    "surname":"shariati"
}

Read JSON file;

// import * as fs from 'fs';
const fs = require('fs')
fs.readFile('./myFile.json', 'utf8', (err, jsonString) => {
    if (err) {
        return;
    }
    try {
        const customer = JSON.parse(jsonString);
} catch(err) {
        console.log('Error parsing JSON string:', err);
    }
})

customer contains your JSON, and values can be accessed by customer.name;

Write to JSON File

Let's say you have an update on your JSON object such as below;

const updatedJSON = {
    "name":"arif updated",
    "surname":"shariati updated"
}

Now you can write to your file. If file does not exist, it will create one. If already exists, it will overwrite.

fs.writeFile('./myFile.json', JSON.stringify(updatedJSON), (err) => {
    if (err) console.log('Error writing file:', err);
})

Upvotes: 3

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

First of all, the browser itself doesn't have access to the filesystem, so you won't be able to achieve that using your react app. However, this can be achieved if you use Node.js(or any other FW) at the backend and create an API endpoint which can help you to write to the filesystem.

Secondly, if you wanted to only do things on the frontend side without creating an extra API just for saving the data in a JSON file which I think is not necessary in your case. You can use localstorage to save the data and ask the user to download a text file using this :

TextFile = () => {
    const element = document.createElement("a");
    const textFile = new Blob([[JSON.stringify('pass data from localStorage')], {type: 'text/plain'}); //pass data from localStorage API to blob
    element.href = URL.createObjectURL(textFile);
    element.download = "userFile.txt";
    document.body.appendChild(element); 
    element.click();
  }

Now, To use local storage API you can check here - https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

Upvotes: 11

Nafis
Nafis

Reputation: 1030

Importing and reading from json can be like:

import data from ‘./data/data.json’;

then use .map() to iterate data.

for writing locally you can use some libraries like https://www.npmjs.com/package/write-json-file

Upvotes: 2

Related Questions