Hello, please tell me how can I convert a string into an array of objects? There is a string
{ _id: 57fa6bd8cc9b4a17d085f53a, title: 'max', private: true }, { _id: 57fa6e10b8455715f48e793b, title: 'room1', private: false }, { _id: 57fa6e25b8455715f48e793c, title: 'room2', private: false } Team
var test = JSON.parse(str); Returns an error
SyntaxError: Unexpected token _.
If JSON.parse run JSON.stringify() before JSON.parse , then there is no error, but the exact same string is returned.
Update
I get a list of rooms from the database and send it to the render.
if (req.user){ mongoose.model('Room') .find() .select('title private') .exec(function(err,rooms){ roomsObj = rooms; res.render('chat.ejs', { isAuthenticated: req.isAuthenticated(), user: req.user ? req.user : null, rooms: roomsObj }); }); } else res.json("You should log in!"); Unfortunately, I did not understand how to transfer data using sockets from the route.js file to server.js. I decided to try to transfer to the client and from the client already on server.js. Since the object in this form (<% = roomsObj%>) is not transmitted, we had to shove it into a string. Client code
socket.emit('send_rooms', rommsObj = '<%= roomsObj %>');
_id, i.e. without ', which indicates the number in this field, and here there are both numbers and letters, which is invalid json. If there are only numbers in_id, then everything is ok. - MrFylypenko pm