I have a file in format .txt, my problem is how to transform text from this file to JSON format (I want to send this json to the server in future)
I have , and get this file from this place
I am using only React and Redux. NOT JQUERY
Here is code when I upload a file from the user:
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 file is like this:
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
Thanks for answers!
:is the name of the property, anything afterwards is the content. So you can create an empty object, and gradually add properties from the file to it. When you get to an empty line, it's time for a new object. Add each object to an array when you've created it. When you get to the end, stringify the array and there's your JSON.