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?
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.