2

I have an array value which is coming from database as an string. I need to convert it into an array. When I check my value in console I can see value as

"[["COL1","COL2","COL3"],["COL4","space,"COL5"]]"

In order to perform my operations I need it to be in below structure

[["COL1","COL2","COL3"],["COL4","space,"COL5"]]

I have already tried JSON.parse() and parseJSON

Expected Result :

[["COL1","COL2","COL3"],["COL4","space,"COL5"]]

Actual Result :

"[["COL1","COL2","COL3"],["COL4","space,"COL5"]]"
5
  • 7
    JSON.parse ?! Commented Apr 16, 2019 at 12:13
  • Hint: JSON.parse Commented Apr 16, 2019 at 12:13
  • JSON.parse() should work fine, how did you use it? Commented Apr 16, 2019 at 12:22
  • i used it like JSON.parse("[['COL1','COL2','COL3'],['COL4','space,'COL5']]") Commented Apr 16, 2019 at 12:32
  • @ManishMayank you have one missing " after space Commented Apr 16, 2019 at 12:43

2 Answers 2

5

You need to remove the outer quotes from your string, then pass the value to JSON.parse() to get the array.

Also, you have to quote each item correctly, "space should be "space".

You can sanitize the string with String.prototype.replace() (assuming the quoting of space has been fixed in the DB):

const data = '"[["COL1","COL2","COL3"],["COL4","space","COL5"]]"';

const dataSanitized = data.replace(/^"|"$/g,"");

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

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

9 Comments

Euh.. okay.. eval.. okay.. However, I would add a little warn. Edit: nevermind, you did that already. The suggestion that eval works as well is interesting, just worth mentioning that between the two methods, the first one is the one you should use :P
@Syed Mehtab Hassan, I added an explanation about the string syntax issues.
data is coming from db. I can edit the inner quotes but outer quote is getting generated automatically
@Manish Mayank, I updated the answer to show how to sanitize the string and get the array
This is what i am getting in my console window var layoutArray = data.Layout; undefined layoutArray "[["COL1","COL2","COL3"],["COL4","space,"COL5"]]" dataSanitized = layoutArray.replace(/^"|"$/g,""); "[["COL1","COL2","COL3"],["COL4","space,"COL5"]]" JSON.parse(dataSanitized) VM7762:1 Uncaught SyntaxError: Unexpected token C in JSON at position 40 at JSON.parse (<anonymous>)
|
-1

I would suggest you do parse

JSON.parse('[["COL1","COL2","COL3"],["COL4","space","COL5"]]')

i would not suggest eval as i just read an article about "how eval is evil" https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/

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.