【问题标题】:How to read a local JSON file, from the browser?如何从浏览器读取本地 JSON 文件?
【发布时间】:2020-01-18 04:33:32
【问题描述】:

我知道这个问题之前已经讨论过,但是我找到的所有解决方案都是几年前的,并且不起作用。

我需要做的是从我的 React 应用程序的公共目录中的 JSON 文件加载一些配置字段。只是一个静态资产,构建过程之外

当我尝试使用 AJAX 获取它时,我收到“意外令牌':'”错误。我的 config.json 文件看起来就像这样:

{
    "name": "yoyo"
}

它位于 create-react-app 程序的公共目录中。有什么办法可以做到吗?

编辑:一切正常,我只是犯了一些愚蠢的错误

【问题讨论】:

  • 你提交的json没有问题。您需要向我们展示您是如何读取它的,以及您是如何尝试解析它的。
  • 你能发布你的代码吗?
  • 这能回答你的问题吗? read local JSON file into variable
  • 谢谢你,我只是似乎有一些错误..解决了。

标签: javascript json


【解决方案1】:

为什么不直接导入而不是请求? 如果您出于任何原因这样做,您是否尝试过 JSON.parse 之类的方法?

【讨论】:

    【解决方案2】:

    当我注意到您想从项目的公共目录加载 JSON 文件时,我更新了我的问题。

    为此,请使用fetch 并从public 文件夹加载文件,然后将其设置为在您的主要组件中使用(例如:App.js)。

    这是一个使用 React Hooks 的示例:

    import React from "react";
    import "./styles.css";
    
    export default function App() {
      const [characters, setCharacter] = React.useState(null);
    
      React.useEffect(() => {
        fetch("names.json")
          .then(results => results.json())
          .then(character => setCharacter(character));
      });
      return (
        <div className="App">
          <h1>Star Wars names!</h1>
          <ul>
            {characters.map(character => (
              <li key={character.name}>{character.name}</li>
            ))}
          </ul>
        </div>
      );
    }
    
    

    Working example using the new useEffect hook here

    Working example using good old componentDidMount here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多