【问题标题】:"SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data" why? [closed]“SyntaxError:JSON.parse:JSON 数据第 1 行第 1 列的意外字符”为什么? [关闭]
【发布时间】:2022-01-14 03:50:29
【问题描述】:

解析 json 文件后出现此错误。在解析之前,它在 output(tag p) 中显示了 json 文件。

index.js:

import React from "react";
import ReactDOM from "react-dom";
import text from "./json.js";

const cities = JSON.parse(text);

class App extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            value: '',
            hint: ''
        }
    }

    handleChange = (e) => {
        this.setState({
            value: e.target.value
        });

    }

    render() {
        return (
            <div>
                <p>{cities}</p>
                <input value={this.state.value} placeholder={this.state.hint} onChange={this.handleChange}/>
            </div>
        );
    }
}

ReactDOM.render(<App/>, document.getElementById("root"));

json.js:

(function getJson(){
    const xhttp = new XMLHttpRequest();
    xhttp.onload = function (){
        export const text = this.responseText;
        }
    xhttp.open("GET", "./cities.json");
    xhttp.send();
})()

cities.json:

https://www.uplooder.net/files/d5f677d8df6a69e6bd17dba5916ee4d0/cities.json.html

【问题讨论】:

  • 欢迎来到 SO!您的整个问题(包括任何必要的代码/文本,例如cities.json 的最小示例)必须您的问题中,而不仅仅是链接。三个原因:人们不应该去场外帮助你;某些网站被某些用户屏蔽;和链接腐烂,使问题及其答案对未来的人们毫无用处。请在问题中输入minimal reproducible example in。更多:How do I ask a good question?Something in my web site or project doesn't work. Can I just paste a link to it?
  • 另外,json.js 和它有什么关系?从第一个代码块可以看出它没有被使用。
  • @T.J.Crowder 哎呀!!我犯了一个错误!我必须写[从“./json.js”导入文本]。我编辑了。
  • @T.J.Crowder 我的第二个错误,我没有将 json.js 放在 src 文件夹中。我现在放了那个。我放置了指向 json 文件的链接,因为我的 json 文件很长。我应该如何放置这些文件?
  • 这个问题完全不正确,现在这个答案也不正确,太浪费时间了,对你最好的建议是确保你的问题也正确,如果会,不要编辑问题更改整个答案,但改为创建另一个问题

标签: reactjs json


【解决方案1】:

json.js 有一个语法错误:export 声明只能出现在模块的顶层,但你的声明在另一个函数内的回调函数内。

如果您使用的是捆绑器,它可能会让您直接使用 import 导入 cities.json(详细信息因捆绑器而异)。

如果没有,如果您的环境支持,您可以使用top-level await

const getCitiesText = async () => {
    const response = await fetch("./cities.json");
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return await response.text();
};
export const text = await getCitiesText();

这会根据您的需要导出文件的文本,但如果您想导出解析的数组,则可以使用json() 而不是text()(并且可能会更改导出的名称):

const getCities = async () => {
    const response = await fetch("./cities.json");
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return await response.json();
};
export const cities = await getCities();

如果你必须支持没有顶级await的环境,你不能导出cities.json的内容,你只能导出该内容的一个promise

const getCities = async () => {
    const response = await fetch("./cities.json");
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return await response.json();
};
export const citiesPromise = getCities(); // No `await` here

任何导入citiesPromise 的东西都必须await 才能获得实际内容。

【讨论】:

    【解决方案2】:

    你想达到什么目的? 1.你的json文件是一个数组,所以你必须映射它来单独渲染它们,2.不需要解析json文件,因为它已经是一个json,试试这个代码并将它粘贴到你的index.js中。

    import React from "react";
    import ReactDOM from "react-dom";
    import "./styles.css";
    import text from "./cities";
    
    class App extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          value: "",
          hint: ""
        };
      }
    
      handleChange = (e) => {
        this.setState({
          value: e.target.value
        });
      };
    
      render() {
        return (
          <div>
            {text.map((city) => (
              <p>{city}</p>
            ))}
            <input
              value={this.state.value}
              placeholder={this.state.hint}
              onChange={this.handleChange}
            />
          </div>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      相关资源
      最近更新 更多