4

I have to read JSON file using React.js which is stored in local drive in Mac. I tried using fetch() api but I get data undefined. Heres my code.

fetch('http://localhost:300/107k.json')
    .then(req => console.log(req))
    .then(data => console.log(data))

I am getting data as undefined. How will I be able to read JSON file in react.js?

1
  • Have you placed the json file in root path for your local server? Commented Jul 2, 2017 at 3:11

2 Answers 2

12

Just use import instead

import react from 'react'

//... rest of imports

import MyJson from '../path/to/json/107k.json';
Sign up to request clarification or add additional context in comments.

5 Comments

But the problem is I cannot import outside src
@AkashSateesh does your server (localhost:300) serves 107k.json? Also, I think you might want to use port 3000 instead because port numbers below 999 are usually reserved.
Sorry its 3000 only. I am using webpack server of react
What happens when you access localhost:3000/107k.json in your web browser, do you see the data? is 107k.json too big to be placed in your react project?
Beware of importing if your data changes as importing will cache the content
5

The json() method of the Body mixin takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON.

fetch('http://localhost:300/107k.json')
  .then(res => res.json())
  .then(data => console.log(data))

2 Comments

I am getting it as XML format. res.json() parsing gives error
This is the right way, make sure your json is valid via jsonlint.com or something similar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.