无法在反应中导入JSON

时间:2019-11-13 21:59:31

标签: javascript json reactjs

我正在确定这是一个愚蠢的问题,但我似乎找不到解决办法。

我有一个React应用程序,我正在尝试导入JSON文件。在这里:

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

这是反应代码:

import React, { Component} from 'react'

import words from 'Assets/Words.json'

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

export default class WordsGen extends Component {
  ...

分别打印两个console.log

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

undefined

我正在使用json文件在应用中添加更多语言,但是我不明白为什么仅打印words时可以看到属性ita以及尝试打印时的原因打印words.itawords["ita"]我不确定。

我想念什么?

2 个答案:

答案 0 :(得分:6)

应该是:

words.words.ita

您要导入为“单词”,然后该对象具有单词对象。更改导入名称可能更清楚:

import MyJson from 'my.json';

console.log(MyJson.words.ita)

答案 1 :(得分:0)

因为导入的对象words包含整个json。当你写

import words from 'Assets/Words.json';

它将变为

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

这就是为什么您的对象words实际上没有属性ita的原因。这就是为什么它将返回undefined

您需要写words.words.ita。为了获得更好的代码风格:

/// 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