cbdeveloper
cbdeveloper

Reputation: 31485

How to access a JSON static file imported with Webpack?

I have this JSON static file in my project structure:

someFile.json

The JSON is an stringified version of an array of objects: [{...},{...},etc]

I'm importing it with Webpack (v 4.41.2) as:

import '../someFile.json'; <----- This is in my App.js file

But now I want to access it inside my App so I can parse it back into array and use it. How can I do it?

This doesn't seem to work:

import myJSONfrom '../someFile.json';
const parsedJson = JSON.parse(myJSON);

function App() {
  // USE parsedJSON
}

I get this error:

Uncaught SyntaxError: Unexpected token u in JSON at position 0

JSON File content:

[{"code":"STOCK","date":"2016-05-19T00:00:00.000Z","open":1240,"max":12430,"min":1240,"avg":12140,"close":12140,"numTrades":12,"amountTraded":120,"volume":121400,"quoteFactor":100},...OTHER OBJECTS....]

Note: This is a React app.

Upvotes: 0

Views: 98

Answers (1)

cbdeveloper
cbdeveloper

Reputation: 31485

Just found out what was wrong.

import myJSON from '../someFile.json';     // THIS DOES WORK
// const parsedJson = JSON.parse(myJSON);  // DON'T DO THIS. IT'S ALREADY PARSED

function App() {
  // USE parsedJSON
}

So basically you can do:

import parsedJSON from '../someFile.json';     // THIS DOES WORK

function App() {
  // USE parsedJSON
}

Upvotes: 1

Related Questions