3

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?

2 Answers 2

7

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)
Sign up to request clarification or add additional context in comments.

1 Comment

In theory, you could also use object spreading to import it with import { words } from 'my.json'. Then it could be used as the author intended (words.ita).
0

Because your imported object words contains whole json. When you write

import words from 'Assets/Words.json';

it will become

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

That's why your object words doesn't really have property ita. That's why it will return undefined.

You need to write words.words.ita. For better code-style:

/// words.json
{ 
   "ita":[ 
       "ora",
       "via",
       "dio",
       "sud",
       "don",
       "zia"
      ]
}
import words from 'Assets/Words.json';
words.ita // then your code

/// or even better with new es6 destructing
import {ita = []} from 'Assets/Words.json';

ita // do anything that you want

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.