History-Economy
History-Economy

Reputation: 25

How to convert space delimited multiple lines string to json with Javascript?

I am working on a web application where users can copy their excel data (multiple rows with 2 columns) onto a website's text area. When clicking submit button on the same page, it will covert the excel data to JSON, displays the JSON in a different text area on the same web page.

I already got a HTML page going, just not certain how to write the convert code. (Code below)

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset = "utf-8" />

      <title>Convert</title>
    </head>
    <body>
      <h1>Convert Table Data (2 Columns) To JSON</h1>

      <button onclick="convert()">Convert to JSON</button>
      <br><br>

      <textarea id="inputText" rows="50" cols="100"></textarea>
      <textarea id="outputText" rows="50" cols="100" readonly></textarea>

      <script>
        var textarea = document.getElementById("inputText");
        var textarea2 = document.getElementById("outputText");
        function convert() {
           // textarea2.value = textarea.value.convertToJSON......
        }
      </script>
    </body>
    </html>

Here is what the excel data will look like when copied and pasted into a text area:

Amy apples
Betty oranges
Cathy watermelon
Daisy bananas
Edward pears
Fiona grapes

Expected results to be displayed on different text area after submit:

{
 "Amy" : "apples",
 "Betty" : "oranges",
 "Cathy" : "watermelon",
 "Daisy" : "bananas",
 "Edward" : "pears",
 "Fiona" : "grapes"
}

Upvotes: 2

Views: 1958

Answers (3)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92427

Try

function convert() {
  let r= inputText.value.replace(/(\w+) (\w+)/g,'  "$1" : "$2",');
         
  outputText.value =  `{\n${r.slice(0, -1)}\n}`
}
<button onclick="convert()">Convert to JSON</button><br>
<textarea id="inputText" rows="10" cols="30">
Amy apples
Betty oranges
Cathy watermelon
Daisy bananas
Edward pears
Fiona grapes</textarea>
<textarea id="outputText" rows="10" cols="30" readonly></textarea>

Upvotes: -1

weegee
weegee

Reputation: 3399

How about splitting the string and then forEach over the array while putting the keys + values in an object?

// your textarea
let textarea = document.querySelector("textarea")
// the value of textarea
let value = textarea.value
// split the string from line breaks, so you have arrays of strings seperated from line breaks
let keys = value.split("\n")
// create an object to store the value on
let obj = {}
keys.forEach((val,index) => { // foreach the array
  let splitString = val.split(" ") // split the "Amy apples" into [Amy,apples]
  splitString[1] ? obj[splitString[0]] = splitString[1] : ""
})
//return and log them
console.log(obj)
<textarea>
Amy apples
Betty oranges
Cathy watermelon
Daisy bananas
Edward pears
Fiona grapes
</textarea>

Upvotes: 0

Ori Drori
Ori Drori

Reputation: 191976

You can trim the string, then split it by \n to an array of strings, map the array and split the items by space. Now you can convert the array of arrays to an object with Object.fromEntries():

const str = `Amy apples
Betty oranges
Cathy watermelon
Daisy bananas
Edward pears
Fiona grapes`

const result = Object.fromEntries(str.trim().split('\n').map(s => s.split(' ')))

console.log(result)

Upvotes: 2

Related Questions