Home > Enterprise >  Problem with import json to variable in React
Problem with import json to variable in React

Time:10-29

I'm new in React and I'm trying to import and save in variable a selected JSON data

[...]

const languageToSet = "polish";
const lang = {
    promiseToSetLanguage: function(lang){
        return new Promise((resolve, reject) => {
            import language from `./languages/${languageToSet}_lang.json`
            language = JSON.parse(language)
            if (language.welcome) {
                console.log('Works fine')
                resolve(true)
            } else{
                reject(false)
            }
        })
    }
}
lang.promiseToSetLanguage()

[...]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Console throw me a error: "'import' and 'export' may only appear at the top level" but i need to load a JSON file selected by user. I used 'import' and 'require' method.

Thanks for your help, best regards.

CodePudding user response:

I think that fetch might be the answer here.. Try to use

return new Promise(async (resolve, reject) => {
            const rawJsonFile = await fetch(`${file_from_user}`);
            const jsonFile = await rawJsonFile.json();
            if (jsonFile.welcome) {
                console.log('Works fine')
                resolve(true)
            } else{
                reject(false)
            }
        })

If it still wont work, you can always use xhr

CodePudding user response:

In most cases you get this error when you are missing a closing bracket. check your code again and see if there is a closing bracket.

  • Related