简体   繁体   中英

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

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)

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>

You can use String.prototype.split to transform your text into rows by separating on line breaks \n . You can then reduce that array into an object which matches your required output.

 const excel = document.getElementById("excel"); excel.addEventListener("change", function handleExcelInput(event) { const rows = event.target.value.split("\n"); const json = rows.reduce(function rowToObject(acc, row) { const [key, value] = row.split(" "); // ["Amy", "apples"] acc[key] = value; return acc; }, {}); console.log(json); });
 <textarea name="" id="excel" cols="30" rows="10"></textarea>

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM