4

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

11
  • The error literally states what the problem is. Your only workaround might be placing the file inside the src folder Commented Aug 21, 2019 at 18:43
  • Alternative: stackoverflow.com/a/55298684/8076386 Commented Aug 21, 2019 at 18:45
  • 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 file Commented Aug 21, 2019 at 18:46
  • ok will look at that link thank you Commented Aug 21, 2019 at 18:47
  • 1
    Why not make fetch call to get json data from that file instead? Commented Aug 21, 2019 at 21:09

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

unfortunately this doesn't allow you to open the json file after building so that i could edit the IP
1

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

1 Comment

Because now the JSON is bundled in with the project, requiring you to rebuild every time it's changed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.