通过请求加载日期fetch()

时间:2019-03-09 10:39:50

标签: reactjs

我有一个JSON文件,我想通过fetch()请求来调用它。我的JSON看起来像这样:

{
  id: { hotelId: "102835", provider: { provider_id: "23", dmnid: 3984 } },
  hotelinfo: {
    name: "Pera Rose Hotel",
    hotelsearch: {
      realname: "Pera Rose Hotel",
      hotelid: 0.0,
      hotelimage: "",
      webserviceimage:
        "http://service.stage.Paximum.com/media/images/product/2/1/2/2/102835-fed561d75dec40ca4d83fd6fc9da9967-jpg/pera_rose_hotel.jpg",
      countryid: 1002247,
      ecountryname: "Turkey",
      ecityname: "Istanbul",
      cityid: 1177676,
      star: 4,
      desc:
        "This hotel is located in the Istanbul's business, shopping and entertainment centre, around a 5-minute walk from the historical Galata Tower, the world's second oldest subway and some 8 minutes' walk away from Taksim Square. In Taksim itself, around 5 minutes' walk from the hotel, guests will find restaurants, bars, shops and clubs. The nearest underground station is Taksim-Meydan, a 10-minute walk away and guests will find the Hagia Sophia, the Topkapi Palace, the Grand Bazaar and the Egyptian Market all around a 15-minute ride away by public transport, as is Sirkeci Station. Istanbul Airport is around 15 km away.",
      enable: "",
      delete: ""
    },
    information: { viewname: "-" }
  }
}

但是我的setState函数未执行,并且出现此错误:

  

SyntaxError:“ JSON.parse:预期的属性值后为','或'}'   对象位于JSON数据的第1行第549列”

这是由于desc域。如您所见,desc中有一些单词,例如Istanbul's,其中有'。有什么办法解决这个问题? (当我使用ajax()请求加载json.bc文件时,没有错误。)

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      library: null,
      perPage: 20,
      currentPage: 1,
      maxPage: null,
      filter: ""
    };
  }

  componentDidMount() {
    fetch("/json.bc", {
      method: "POST",
      body: "cityid=[##cms.form.cityid##]"
    })
      .then(response => response.text())
      .then(text => {
        var Maindata = JSON.parse(text.replace(/\'/g, '"'));
        this.setState(
          state => ({
            ...state,
            data: Maindata
          }),
          () => {
            this.reorganiseLibrary();
          }
        );
      })
      .catch(error => console.error(error));
  }

  reorganiseLibrary = () => {
    const { filter, perPage, data } = this.state;
    let library = data;
    if (filter !== "") {
      // ...
    }
    library = _.chunk(library, perPage);
    this.setState({
      library,
      currentPage: 1,
      maxPage: library.length === 0 ? 1 : library.length
    });
  };

  previousPage = event => {
    this.setState({
      currentPage: this.state.currentPage - 1
    });
  };

  nextPage = event => {
    this.setState({
      currentPage: this.state.currentPage + 1
    });
  };

  handlePerPage = evt =>
    this.setState(
      {
        perPage: evt.target.value
      },
      () => this.reorganiseLibrary()
    );

  renderLibrary = () => {
    const { library, currentPage } = this.state;
    if (!library || (library && library.length === 0)) {
      return <div class="nodata">No Result</div>;
    }
    return library[currentPage - 1]
      .sort((a, b) => a.total - b.total)
      .map((item, i) => <div class="item">{item.id}</div>);
  };

  render() {
    const { library, currentPage, perPage, maxPage } = this.state;
    return (
      <div className="Main-wrapper">
        <div className="wrapper-data">{this.renderLibrary()}</div>
        <ul id="page-numbers">
          <li class="nexprev">
            {currentPage !== 1 && (
              <button onClick={this.previousPage}>
                <span class="fa-backward" />
              </button>
            )}
          </li>
          <li class="controls active">{this.state.currentPage}</li>
          <li class="controls">{this.state.maxPage}</li>
          <li class="nexprev">
            {currentPage < maxPage && (
              <button onClick={this.nextPage}>
                <span class="fa-forward" />
              </button>
            )}
          </li>
        </ul>
      </div>
    );
  }
}

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

1 个答案:

答案 0 :(得分:0)

&#39; html实体替换双引号字符串中的单引号,然后用双引号替换单引号,最后(可选)用单引号替换单引号html实体。

function stringToJSON(str) {

  // convert single qoute inside double qoutes to html entity
  const singleQuoteToEntity = str.replace(/"[^"]+"/g, function(m) {
    return m.replace(/\'/g, '&#39;');
  });

  const replaceSingleQuotes = singleQuoteToEntity.replace(/\'/g, '"');

  return replaceSingleQuotes.replace(/&#39;/g, '\'');

}

const jsonString = "{ 'id': { 'hotelId': '102835', 'provider': { 'provider_id': '23', 'dmnid': 3984 } }, 'hotelinfo': { 'name': 'Pera Rose Hotel', 'hotelsearch': { 'realname': 'Pera Rose Hotel', 'hotelid': 0.0, 'hotelimage': '', 'webserviceimagine': 'http://service.stage.Paximum.com/media/images/product/2/1/2/2/102835-fed561d75dec40ca4d83fd6fc9da9967-jpg/pera_rose_hotel.jpg', 'countryid': 1002247, 'ecountryname': 'Turkey', 'ecityname': 'Istanbul', 'cityid': 1177676, 'star': 4, 'desc': \"This hotel is located in the Istanbul's business, shopping and entertainment centre, around a 5-minute walk from the historical Galata Tower, the world's second oldest subway and some 8 minutes' walk away from Taksim Square. In Taksim itself, around 5 minutes' walk from the hotel, guests will find restaurants, bars, shops and clubs. The nearest underground station is Taksim-Meydan, a 10-minute walk away and guests will find the Hagia Sophia, the Topkapi Palace, the Grand Bazaar and the Egyptian Market all around a 15-minute ride away by public transport, as is Sirkeci Station. Istanbul Airport is around 15 km away.\", 'enable': '', 'delete': '' }, 'information': { 'viewname': '-' } } }";

console.log(JSON.parse(stringToJSON(jsonString)))

在您的App组件中,请执行以下操作

class App extends React.Component {

  ....

  stringToJSON = (str) => {

    // convert single qoute inside double qoutes to html entity
    const singleQuoteToEntity = str.replace(/"[^"]+"/g, function(m) {
      return m.replace(/\'/g, '&#39;');
    });

    const replaceSingleQuotes = singleQuoteToEntity.replace(/\'/g, '"');

    return replaceSingleQuotes.replace(/&#39;/g, '\'');

  }


  componentDidMount() {

    fetch("/json.bc", {
      method: "POST",
      body: "cityid=[##cms.form.cityid##]"
    })
      .then(response => response.text())
      .then(text => {
        var Maindata = JSON.parse(this.stringToJSON(text));
        this.setState(
          state => ({
            ...state,
            data: Maindata
          }),
          () => {
            this.reorganiseLibrary();
          }
        );
      })
      .catch(error => console.error(error));
  }
  ....