如何使用React和JavaScript将.txt文件转换为JSON

时间:2019-06-17 11:45:42

标签: javascript json

我有一个.txt格式的文件,我的问题是如何将文本从此文件转换为JSON格式(我希望将来将此json发送到服务器)

我有,并且从这个地方获取此文件

我只使用React和Redux。不是JQUERY

这是我从用户上传文件时的代码:

class AddFilm extends Component {
    constructor() {
      super();
      this.state = {};
    }
    handleselectedFile = event => {
      this.setState({
        selectedFile: event.target.files[0],
        loaded: 0
      });
    };
    openFile(event) {
      let input = event.target;

      let reader = new FileReader();
      reader.onload = function() {
        let text = reader.result;
        console.log(reader.result.substring(0));

      };
      reader.readAsText(input.files[0]);
    }
    render() {
      return (
        <div className="import-film container">
          <div className="import-form">
            <h3>Choose file to import</h3>
            <input
              type="file"
              name=""
              id=""
              onChange={event => this.openFile(event)}
            />
            <button onClick={this.handleUpload}>Upload</button>
          </div>
        </div>
      );
    }
  }
);
export default ImportFilm;

.txt文件是这样的:

Title: Blazing Saddles
Release Year: 1974
Format: VHS
Stars: Mel Brooks, Clevon Little, Harvey Korman, Gene Wilder, Slim Pickens, Madeline Kahn

Title: Casablanca
Release Year: 1942
Format: DVD
Stars: Humphrey Bogart, Ingrid Bergman, Claude Rains, Peter Lorre

Title: Charade
Release Year: 1953
Format: DVD
Stars: Audrey Hepburn, Cary Grant, Walter Matthau, James Coburn, George Kennedy

Title: Cool Hand Luke
Release Year: 1967
Format: VHS
Stars: Paul Newman, George Kennedy, Strother Martin

感谢答案!

2 个答案:

答案 0 :(得分:2)

只要您的txt文件是一致的,类似的事情就会起作用:

const data = `Title: Blazing Saddles
Release Year: 1974
Format: VHS
Stars: Mel Brooks, Clevon Little, Harvey Korman, Gene Wilder, Slim Pickens, Madeline Kahn

Title: Casablanca
Release Year: 1942
Format: DVD
Stars: Humphrey Bogart, Ingrid Bergman, Claude Rains, Peter Lorre

Title: Charade
Release Year: 1953
Format: DVD
Stars: Audrey Hepburn, Cary Grant, Walter Matthau, James Coburn, George Kennedy

Title: Cool Hand Luke
Release Year: 1967
Format: VHS
Stars: Paul Newman, George Kennedy, Strother Martin`

console.log(data.split('\n\n').map(entry => {
  const obj = {}
  entry.split('\n').forEach(keyValue => {
    const split = keyValue.split(": ")
    const key = split[0]
    const value = split[1]
    obj[key] = key === "Stars" ? value.split(", ") : value
  })
  return obj
}))

答案 1 :(得分:0)

很久以前就问过这个问题,但是最近我正在寻找类似问题的解决方案,所以我找到了一种简单的方法来处理它。因此,如果有人仍然对此感兴趣,那就在这里。

您无需使用所有这些操作,而只需使用JSON.parse。

const convertToJSON = (data) => {
  return data.split('\n\n').map(entry => {
    return JSON.parse(entry);
  });
}

此解决方案对我有用。我希望它也对您有用。