34

I have a problem since two days; I want read a local JSON from my public folder on my React application created with react-app.

This is my project structure:

  • public

    • data

      • mato.json (my .JSON file)
  • src

    • components

      • App.js

Why I put my file in public folder? If I build my project with file in src folder, my file will be include in the generated main.js by the command yarn build.

I want modify my json file without always rebuild my app.

So I can't use code like:

import Data from './mato.json'

…or:

export default { 'mydata' : 'content of mato.json'}
import data from 'mydata';

I tried to fetch my .json file but "file scheme" isn't friend with fetch() & chrome..

(Chrome error: “index.js:6 Fetch API cannot load file:///D:/projects/data/mato.json. URL scheme "file" is not supported.”)

This is my code for fetch:

fetch(`${process.env.PUBLIC_URL}/data/mato.json`)
.then((r) => r.json())
.then((data) =>{
    ReactDOM.render(<App appData={JSON.stringify(data)}/>, document.getElementById('root'));
})

It's only works with Firefox. I also tried mode: 'cors' does not better.

And of course I don't have any server — it's a local project — so if someone knows how I can read my JSON file locally I will much appreciate.

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Kevin
  • 482
  • 1
  • 4
  • 10

5 Answers5

43

I think your fetch argument is wrong. It should be

fetch('data/mato.json')
Jason Roman
  • 8,146
  • 10
  • 35
  • 40
Quentin
  • 586
  • 8
  • 10
8

You also need to pass in some headers indicating the Content-Type and Accept as application/json to tell your client that you are trying to access and accept some JSON resource from a server.

  const getData=()=>{
    fetch('data/mato.json'
    ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    }
    )
      .then(function(response){
        console.log(response)
        return response.json();
      })
      .then(function(myJson) {
        console.log(myJson);
      });
  }
  useEffect(()=>{
    getData()
  },[])
Blessing
  • 2,450
  • 15
  • 22
5

As long as data files are placed in public folder, it should work in Chrome also as in my project. So, fetch('data/mato.json') is enough for it.

Lex Soft
  • 2,308
  • 2
  • 13
  • 13
1

give your JSON file name which is present in the public folder and store the data links

componentDidMount() {
    fetch("./url.json")
      .then((res) => res.json())
      .then((data) => {
        this.setState({ links: data });
        console.log(this.state);
      });
  }
-1

why using fetch? I think the speed is slow... I think this solution would be better... you can add this line into your index.html:

<script type="text/javascript" src="settings.js"></script>

then in settings.js you can do this:

 window.globalTS= {
  "site_url": "hi.com",
  "home_url": "hello.com"
};

now in your components you can get to variables like this:

console.log(window.globalTS.site_url);

share and comment me your idea, thanks!

Hamid Alinia
  • 59
  • 10
  • This answer is exactly the same as [this answer](https://stackoverflow.com/a/67848787/14267427). If you feel this question is a duplicate, give it a flag, don't just copy and paste the same answer all over the network. – Tyler2P Jun 05 '21 at 11:32
  • @Tyler2P thanks, I just gave a flag. both questions has one meanings, just different keywords: https://stackoverflow.com/a/67848787/5008599 – Hamid Alinia Jun 05 '21 at 13:46