Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert html textarea value to json?

Client

.. some form
<textarea name="data"></textarea>

I will type to textarea like below

{title: 'Hello one!', author: 'someone'}
{title: 'Hello two!', author: 'mygf'}
{title: 'Hello three!', author: 'darthvader'}

And finally submit the form,

Server

Server will get above like

'{title: \'Hello one!\', author: \'someone\'}\r\n
{title: \'Hello two!\', author: \'mygf\'}\r\n
{title: \'Hello three!\', author: \'darthvader\'}\r\n'

At this point how can I convert it?

I tried:

 var dataArray = req.body.data.split('\r\n');
 for (var i=0; i< dataArray.length; i++){
     console.log(dataArray[i].title)  // err because dataArray[i] is not obj
 }

How can I make objectdarray correctly?

like image 865
ton1 Avatar asked Dec 21 '25 11:12

ton1


1 Answers

What you have is not valid JSON. If you use valid JSON (keys and string values wrapped in double-quotes), then you can simply use JSON.parse():

var data = '{"title": "Hello one!", "author": "someone"}\r\n{"title": "Hello two!", "author": "mygf"}\r\n{"title": "Hello three!", "author": "darthvader"}';
var dataArray = data.split('\r\n');

for (var i=0; i<dataArray.length; i++){
  dataArray[i] = JSON.parse(dataArray[i]);
  console.log(dataArray[i]);
}

If you want to allow invalid JSON, you'll need to analyze the strings and figure out where the keys & values are and add them to a newly created object.

like image 163
skyline3000 Avatar answered Dec 24 '25 01:12

skyline3000



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!