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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With