2
votes

I have a ipAddress.json file that has the contents:

{
  "ipAddress": "11.111.111.111"
}

In the public folder i put that ipAddress.json file into an "ipAddress" folder so the path looks like "public/ipAddress/ipAddress.json"

But I cannot read this file. I am trying

const ipAddress = (require(process.env.PUBLIC_URL + '/ipAddress/ipAddress.json')).ipAddress;

using "json-loader" common library.

How do I get this to work? According to (Using the Public Folder) it should work just fine.

But I get this error:

Module not found: You attempted to import /ipAddress/ipAddress.json which falls outside of the project src/ directory. Relative imports outside of src/ are not supported.

Thank you for any help

2
The error literally states what the problem is. Your only workaround might be placing the file inside the src folderRohit Kashyap
when I build the project I need to be able to edit that ipAddress.json file which is why I want to put it in the public folder but if I put it into the src folder when I build u cannot access that fileuser1189352
ok will look at that link thank youuser1189352
Why not make fetch call to get json data from that file instead?Arturas

2 Answers

1
votes

If its just a json object you should be able to create a js file with the data inside a const object. Then export the const as a module.

New JS file to create:

const ipAddressJson = {
    ipAddress: "11.111.111.111"
};

module.exports = ipAddressJson;

Inside the file you want the json object:

import ipAddressJson from 'path-to-the-js-file-above';

https://codesandbox.io/embed/tender-bash-2hjei

1
votes

Why not put your JSON files into your project scope? For example, if you have created the react app using create-react-app, the src folder will be the default project scope.

Put your JSON files into some folder like src/data and simply:

import data from '../data/somefile.json