3

I have a project I'm working on that implements MySQL, React and Express.js. I need to save an array into MySQL, but there are currently no ways to save an array, as far as I could see, so I was forced to convert it into a string. When I get it back from Express to the client, it's obviously a string, so I can't access the data. This array is used for a graph, mainly. What are some of the ways I can convert this string back to an array?

1
  • 1
    Can you please provide code sample of the string you store? And have you considered saving the array's elements in a different table and use many-to-one relation? Commented Mar 2, 2019 at 8:49

3 Answers 3

4

You can use JSON.parse() to convert a string into an array.

const response = "[1,2,3]";

console.log(JSON.parse(response));

Sign up to request clarification or add additional context in comments.

Comments

2

You can store your json object (including arrays )in form of text in mysql database.What you have to do is JSON.stringify("your array") and persist it in database.And while you are retrieving it back from database you can JSON.parse() to get it in form of JavaScript object

Comments

1

Depends on how you formed the string. If you used , for joining the elements, then you can use javascript's string.split() method.

let str = '1,2,3,4';
let arr = str.split(',');

Just pass in whatever delimiter you used to join the elements.

OR

If you're saving elements as a json string, then use JSON.parse(str) as shown by Nils Kähler in his answer

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.