1

I have the following string:

"[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]"

and I want to convert it to array of object

[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]

I've tried to do many things but I could not

        function nextQuess() {
        var ffa = JSON.stringify("<%- hola %>");  // from ejs variable "[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]"
        // var ff = JSON.parse([ffa])
        // console.log('hello', ff);
        console.log("Hello", ffa);
    } 

2 Answers 2

4

You need to replace ' by " and then parse

 '(.*?)'(?=(,|\])
  • '(.*?)' - Match ' followed by anything zero more time ( Lazy mode ) ( Capture group 1)
  • (?=(,|\])) - Match must be followed by , or ]

let str = "[['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]"

let replacedString = str.replace(/'(.*?)'(?=(,|\]))/g, "\"$1\"")
let final = JSON.parse(replacedString)

console.log(final)

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

2 Comments

I receive this error VM3089:1 Uncaught SyntaxError: Unexpected token ` in JSON at position 0 at JSON.parse
@RafaelPereira where you're trying to run this code. i tried in codepen, console and vscode, i don't see this error occurring, BTW you can drop that part where i replaced " by ` see the updated answer
0

Use JSON.stringify(json) and then JSON.parse()

let jsonString = JSON.stringify([['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]);
let array = JSON.parse(jsonString);
console.log(array);

Or you can also try eval() method

let jsonArray = eval([['ABB','ACC','ADD'],['FGG','FHH','FJJJ'],['MNN','MOO','MPP']]);
console.log(jsonArray);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.