当前位置:  开发笔记 > 编程语言 > 正文

Can't import JSON in react

如何解决《Can'timportJSONinreact》经验,为你挑选了1个好方法。

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?



1> ageoff..:

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)

推荐阅读
360691894_8a5c48
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有