I have been trying to simply read a json file within a .js script in an ionic framework. My repository file structure is as per the following:
- public/...
- resources/...
- src/
- components/...
- pages/
- Tab1.css
- Tab1.tsx
- utils
- configs/config.json
- utils.js
- require.js
When I debug, I load an object from utils.js called by Tab1.tsx. The debugger successfully goes into the utils.js and calls "read_json" function as part of object creation, which looks like this:
export function read_json(){
let json_data = fetch('./configs/config.json')
.then((response) => response.json())
.then((json) => console.log(json));
console.log(json_data)
}
I get the following result: Promise {[[PromiseState]]: 'pending', [[PromiseResult]]: undefined}
. I tried using the "await" function and the result was the same. I also tried using the require(‘./configs/config.json’), but then got error message Uncaught ReferenceError ReferenceError: require is not defined
despite having a require.js in my structure.
When I was loading the json outside of ionic framework, I did not have this issue. Could someone help?
2
Answers
This returns a promise that resolves as a Response object
This returns a promise that resolves as the result of parsing the JSON from the response body
This logs the JavaScript object/array/other value that you get from parsing the JSON (it doesn’t log JSON, you parsed in in the previous step!) and then returns a promise that resolves as the return value of
console.log(...)
which isundefined
and not what you wantUsing
then
to do this you would want:Then you log the promise object:
Your attempt to use it probably failed because of
console.log
returningundefined
as mentioned above.await
is a keyword, not a function. Using it to handle all your promises instead of mixing it withthen
makes life much easier.This all assumes that your URL is right. Generally the contents of
src
doesn’t contain data served by a web server and you’d want to store the.json`` file under
public`.You are using ECMAScript modules (using
import/export
) not CommonJS modules (which are Node.js’ default module format and which work with a function namedrequire
) and also not AMD modules (which are what Require.JS uses, and which also use a function namedrequire
but not one that is compatible with CommonJS modules).You should return the value. Use this code