0

I want to parse an external JSON file into my react app.

Here, I created a working example of what I want in Codesandbox.io:

https://codesandbox.io/s/morning-tdd-we2v3?file=/src/App.js

In this example, I am using some JSON data inside of the application but wanted to parse this data from an outside source file here: https://raw.githubusercontent.com/Forschung/AmbeentData/main/modems.json

I tried some ways but could be successful.

Best

5
  • 1
    Consider using fetch? developer.mozilla.org/en-US/docs/Web/API/Fetch_API --- "I tried some ways but could be successful." please edit the question and show those efforts? Commented Jan 26, 2021 at 21:57
  • I tried that, but it seems no luck for me :/ Commented Jan 26, 2021 at 21:58
  • Share that effort as an minimal reproducible example. "no luck for me" is not helpful. Commented Jan 26, 2021 at 21:59
  • I already did, please click the first link and you will see that. And the problem solved by @milad-reisi Commented Jan 27, 2021 at 6:29
  • Links to offsite resources are not helpful when describing he problem. Please include everything you can in the question itself. Commented Jan 27, 2021 at 9:31

2 Answers 2

1

Your JSON data format is invalid and that the reason for this problem. you can fetch data as pure text and then fix them locally like this.

demo

const [data, setData] = useState([]);

useEffect(() => {
async function getData() {
  fetch(
    "https://raw.githubusercontent.com/Forschung/AmbeentData/main/modems.json"
  )
    .then(function (response) {
      return response.text();
    })
    .then(function (txt) {
      let d = txt.replace(/Brand/g, `"Brand"`);
      d = d.replace(/Model/g, `"Model"`);
      d = JSON.parse(d);
      setData(d);
    });
}
getData();
}, []); 
Sign up to request clarification or add additional context in comments.

Comments

0

'json file is wrong' the correct one should be

"key": "value"

You did this as

key: "value"

Wrong Json file

[
    { Brand:"Actiontec", Model:"GT784WNV" },
    { Brand:"Actiontec", Model:"MI424WR" },
    { Brand:"AirTies", Model:"Air 4450" }
]

Must Have Json File

[
   {
      "Brand":"Actiontec",
      "Model":"GT784WNV"
   },
   {
      "Brand":"Actiontec",
      "Model":"MI424WR"
   },
   {
      "Brand":"AirTies",
      "Model":"Air 4450"
   }
]

The answer to the second question is that you can make this request very simply using the axios library. I'll leave the sample code and the live example.

Proje Test Link

Sample code

useEffect(() => {
    axios(
      "json link"
    )
      .then((res) => setDatas(res.data))
      .catch((e) => console.log(e))
      .finally(() => console.log('finally'));
  }, []);

Comments

Your Answer

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