0

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!

4
  • @Anon your approach should be to find a way to parse that file. The data is well-formatted and sticks to a fixed pattern, so it shouldn't be too hard. Read it line by line. Each populated line corresponds to an object property. Anything before the : 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. Commented Jun 17, 2019 at 11:53
  • npmjs.com/package/plain-text-data-to-json This is an NPM package that suits your needs. I dont know if you'd like to use it , since you're using redux and react I assume you wouldnt mind using another package Commented Jun 17, 2019 at 11:56
  • @ADyson oh, I know it but don't know how to do it in JS :( Commented Jun 17, 2019 at 11:58
  • @Anon well which part of the process are you stuck with exactly? You've got as far as reading the file data. Now you just need to split the data by newline and by colon characters. Do you not understand how to split a string? Break the problem down into these small steps and everything I've mentioned is a well-understood, simple task in JavaScript. If you don't know how to do a specific one, then it's easy to research. Stop thinking of it as one big job and start thinking of each individual part of the problem, and tackle them one by one. Commented Jun 17, 2019 at 11:59

2 Answers 2

2

Something like this would work, providing your txt file is consistent:

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
}))

Sign up to request clarification or add additional context in comments.

Comments

0

This question was asked long time ago but I was looking for solution for similar problem recently and I found an easy way to deal with it. So, if someone is still interested, here it is.

Instead of using all these manipulations, you can simply use JSON.parse.

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

This solution works for me. I hope it works for you too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.