Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't import JSON in react

I'm having what I'm sure it's a stupid problem but I can't seem to find a way around it.

I have a react application and I'm trying to import a JSON file. Here it is:

{ 
   "words":{ 
      "ita":[ 
         "ora",
         "via",
         "dio",
         "sud",
         "don",
         "zia"
      ]
   }
}

And here's the react code:

import React, { Component} from 'react'

import words from 'Assets/Words.json'

console.log(words)
console.log(words.ita)

export default class WordsGen extends Component {
  ...

The two console.log print, respectively:

{words: {…}}
  words:
    ita: (6) ["ora", "via", "dio", "sud", "don", "zia"]
  __proto__: Object
__proto__: Object

and undefined.

I'm using the json file to put more languages in the app, but I can't understand why when I print just words I can see the property ita inside, and when I try to print words.ita or words["ita"] I get undefined.

What am I missing?

like image 320
ste Avatar asked Aug 14 '26 02:08

ste


1 Answers

Should be:

words.words.ita

You are importing as "words" and then the object has a words object. It might be more clear to change the import name:

import MyJson from 'my.json';

console.log(MyJson.words.ita)
like image 102
ageoff Avatar answered Aug 16 '26 17:08

ageoff