0

Given a string of the format

"(1,(2,3,4),(5,6,(7,8,9,a,(b,c,d))))"

What is the easiest way of converting this into a JavaScript array?

[1, [2, 3, 4], [5, 6, [7, 8, 9, 'a', ['b', 'c', 'd']]]]

The use of both integers and unqutoed strings prevents me from using inbuilt parsing, and the multidimensionality prevents me from using simple splits, or similar.

4
  • Is it guaranteed that all strings will be unquoted, and no reserved characters (commas, brackets & quotes) will exist in the strings? Commented Jan 13, 2019 at 1:34
  • @MTCoster Yep, all of those characters within values are translated into numeric forms, so any comma, bracket, etc. will explicitly be used to define the array shape. Commented Jan 13, 2019 at 1:38
  • They’re all numeric forms? Are they just hex characters or is the base variable? Commented Jan 13, 2019 at 1:40
  • @MTCoster Sorry, every character is not translated to a numerical form, namely only instances of (, ) and , are made into the form &40;, &41; and &44;. I do have access to the serialiser however, so I can add other characters to be reserved, e.g. ". Commented Jan 13, 2019 at 1:42

3 Answers 3

3

One option would be to use a regular expression to turn the parentheses into square brackets, surround the strings with quotes, and then JSON.parse it:

const input = "(1,(2,3,4),(5,6,(7,8,9,a,(b,c,d))))";
const json = input
  .replace(/\(/g, '[')
  .replace(/\)/g, ']')
  .replace(/[a-z]+/g, '"$&"');
console.log(JSON.parse(json));

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

Comments

0

Here's another approach which uses a replaceAll function to replace the brackets from ( -> [ and ) -> ], and makes sure all letters have quotes around them with regex:

const string = "(1,(2,3,4),(5,6,(7,8,9,a,(b,c,d))))";

String.prototype.replaceAll = function(search, replacement) {
  var target = this;
  return target.split(search).join(replacement);
};

const replaced = string.replaceAll("(", "[").replaceAll(")", "]").replace(/[a-zA-Z]+/g, '"$&"');

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

Comments

0

Using a oneliner you can do this

const str = "(1,(2,3,4),(5,6,(7,8,9,a,(b,c,d))))";
const array = JSON.parse(input.replace(/\(|\)/g, (match) => match === ")" ? "]" : "[").replace(/[a-zA-Z-_]/g, '"$&"'));

console.log(array)

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.