skip to Main Content

I have a txt file, which has the following structure

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

I already have file data in string format.
Somehow I must convert it to JSON
I’ve to try split in this way

file.buffer.toString().split('n')

But how should I move on?

2

Answers


  1. Split on the newline character, split each of those strings by the colon symbol. Use reduce and create a new object in the accumulator a when there is a blank line, otherwise set properties in the most recent object in the accumulator for every non-empty [key,value] pair encountered.

    const s = `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(s.split('n').map(i=>i.split(': ')).reduce((a,[k,v]) =>
      (!v && a.push({}) || (a[a.length-1][k]=v), a), [{}]))
    Login or Signup to reply.
  2. You can use this npm library.
    https://www.npmjs.com/package/export-from-json
    Also we can get other formats csv, txt, xls etc.
    You can check my usage example: https://github.com/devStack03/node-csv-json-export

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search