0

I have a nested array stored as a string in my database. After fetching it, it is returned as a string. I need to convert it back to a nested array. JSON.parse does not work for this, unfortunately, I get this error:

VM5481:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 2

Essentially, I need to convert this:

"[['E4', '4n.'], ['D4', '8n'], ['C4', '4n'], ['D4', '4n']]"

to this:

[['E4', '4n.'], ['D4', '8n'], ['C4', '4n'], ['D4', '4n']]

using JavaScript.

Nick
  • 138,499
  • 22
  • 57
  • 95
mlgvla
  • 17
  • 3
  • Thank you! I had trouble finding a similar issue this time, but I will certainly follow these guidelines in the future. – mlgvla Dec 31 '20 at 07:21

1 Answers1

5

When working with JSON, the string literals should be in double quotes " and not single quotes. You can either change whatever is giving you your string to use double quotes (ie: a valid JSON string) or use the .replace() method to change the existing string:

const str = "[['E4', '4n.'], ['D4', '8n'], ['C4', '4n'], ['D4', '4n']]";
const res = JSON.parse(str.replace(/'/g, '"'));
console.log(res);

If you have control over it, I would recommend changing whatever is returning the string over the replace method.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
  • As of now, that's the way the data gets stored. If I have the opportunity to store it as a nested array, I would to begin with, but I was asked to store the nested array as a string for the time being. But this is a very useful solution - my RegEx needed the brushing up! – mlgvla Dec 31 '20 at 07:26
  • @mlgvla No worries. My last comment is mainly referring to how you are creating the string. For instance, if you have a nested array, you can use `JSON.stringify(yourNestedArray)` to convert your nested array into a string and store that. This way, when you need to turn it back into an array, you can use `JSON.parse()` on it without any issues, as JSON.stringify will convert your nested array into a valid JSON string for you, which JSON.parse() expects (so there would be no need to manipulate the string before we try and parse it) – Nick Parsons Dec 31 '20 at 07:30
  • This is good to know. The original data in the database came from a database seed file where the array was manually turned into a string - and in so doing the conversion to single quotes in the nested array elements was necessary. In program use, the nested array will be created by the user and will go through JSON.stringify along with other related data before being POSTed to the database. That might take of things right away before it hits the database. I still may have to account for any seed data that I have to process or find a way to preprocess the seed data if I have to reset the db. – mlgvla Dec 31 '20 at 13:00
  • 1
    I might try changing the double quotes in the seed file to escaped double quotes. That might make JSON.parse happier. – mlgvla Dec 31 '20 at 13:12
  • 1
    FYI - that worked!!! – mlgvla Jan 01 '21 at 02:32