1

Am trying to read a Json file in my react app, but console shows that the url for my json file is 404. Can any one please look into what is wrong in my code

Below is the error shown in browser console. When I open the json url that is shown in network tab, it redirects to the page instead of showing json -

enter image description here

Below is my code -

-

import React from 'react';
import Header from './Header';
import Container from './Container'
import Footer from './Footer'

class App extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
          error: null,
          isLoaded: false,
          products: []
        };
      }
    componentDidMount() {
        fetch("../json/results.json",{
            headers : { 
                'Content-Type': 'application/json',
                'Accept': 'application/json'
               }
        })
        .then(res => res.json())
          .then(
              console.log("--------"),
            (result) => {
              this.setState({
                isLoaded: true,
                products: result.Products
              });
            },
            // Note: it's important to handle errors here
            // instead of a catch() block so that we don't swallow
            // exceptions from actual bugs in components.
            (error) => {
              this.setState({
                isLoaded: true,
                error
              });
            }
          )
      }

    render(){
        const { error, isLoaded, products } = this.state;
        if (error) {
            return <div>Error: {error.message}</div>;
          } else if (!isLoaded) {
            return <div>Loading...</div>;
          } else {
                return(
                    <div>
                    <Header />
                    <br></br>
                    <Container />
                    <ul>
                        {(products || []).map(item => (
                            <li key={item.content_id}>
                            {item.content_id} {item.content_type}
                            </li>
                        ))}
                    </ul>
                    <br></br>
                    <Footer />
                    </div>
                );
            }
    }
}

export default App;

My Json is as below -

{
    "Products": [
        {
        "content_id": "1211122910721",
        "content_type": "AVG_Product_C"
    ]
}
6
  • 1
    Why do you need to use fetch to load your local json? You can import json like how you import modules from library Commented Feb 8, 2019 at 6:22
  • @HemadriDasari am still a beginner, trying to learn React. Am not sure how to import and use JSON in my App.js file Commented Feb 8, 2019 at 6:27
  • Please share folder structure of your app component and Json file. Otherwise it’s difficult to help Commented Feb 8, 2019 at 6:30
  • @HemadriDasari here is my folder structure - ibb.co/pZxkBRv Commented Feb 8, 2019 at 6:32
  • The path looks absolutely right. Are you sure you are getting file not found error? Commented Feb 8, 2019 at 6:40

2 Answers 2

5

Since JSON file is already inside the react application you can import it directly. you can use fetch to get JSON/XML responses from other servers/API

import React from "react";
import Header from "./Header";
import Container from "./Container";
import Footer from "./Footer";
import JSONResult from '../json/results.json';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      products: JSONResult.Products || []
    };
  }
  render() {
    const { products } = this.state;
    return (
      <div>
        <Header />
        <br />
        <Container />
        <ul>
          {products.map(product => (
            <li key={product.content_id}>
              {product.content_id} {product.content_type}
            </li>
          ))}
        </ul>
        <br />
        <Footer />
      </div>
    );
  }
}

export default App;
Sign up to request clarification or add additional context in comments.

2 Comments

am getting the same error even after using your code sample
It generates an error informing: Module '"/path/.../results"' has no default export. In this case I added "resolveJsonModule": true in tsconfig.json inside of "compilerOptions" and import with this pattern: import * as JSONResult from '../json/results.json'; and everything works fine!
0

I faced this situation today. Got to know what was happening. It seems the app is looking for the JSON file at the root level or inside the public folder present at the root level.
And if someone still looking for a solution related to the usage of local JSON (mimicking server calls) then make sure you put the JSON at the root level of your project. So there could be two scenarios I can think of -

  1. If you have a public folder at root level --> I am taking the above scenario mentioned in the question. Your JSON should be present inside /public/json/results.json
  2. If you don't have a public folder --> Put the JSON file at the root level same as your src.

Comments

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.