简体   繁体   中英

Can't get data from simple json file in React

I have local json file from which I have to retrieve data.

That's my code:

 const myReq = new Request('./data.json')
        fetch(myReq)
            .then(rawD=> rawD.json())
            .then(info =>  console.log(info))
            .catch(err => console.log(err))

Like that I get an error SyntaxError: Unexpected token < in JSON at position 0 - on the fetch(myReq) line. And if I remove the rawD.json() row, I have a Response

ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"

etc.

But I can't access the actual data in the json file

If data.json is a local file, meaning you can access it in your file manager where your app is being developed, I would recommend doing something as simple as this:

import data from './data.json' or const data = require('./data.json')

and then use it as usually:

import data from './data.json'

data.map((item) => console.log(item))

If this is going to be an external data.json, you might want to resort to modules such as fetch or axios

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM