Skip to content Skip to sidebar Skip to footer

How Convert String Arrays Of Arrays Into Normal Arrays Without Using JSON.parse

im currently woking on replicating a json parse like function but i have been unable to handle nested string arrays like : ''[a, [b, c, e, g], n]''. I've tried thing like split, r

Solution 1:

This solution works for arrays containing either single characters, or containing other arrays containing only single characters.

const string = '"[a, [b, c, e, g], n]"'.slice(2, -2);
const array = [];
let currArr = array;

for (const char of string) {
  /[a-z]/.test(char) && currArr.push(char);
  /\]/.test(char) && (currArr = array);
  if (/\[/.test(char)) {
    currArr = [];
    array.push(currArr);
  }
}

console.log(array); // [ 'a', [ 'b', 'c', 'e', 'g' ], 'n' ]

When it encounters an opening bracket [ it pushes a new array and pushes all future letters into that array until it encounters a closing bracket ].


Solution 2:

You could implement a rudimentary tokenization parser. You have 4 conditions. This utilizes recursion, so it should work for deeply-nested data.

  • Opening square-bracket
  • White-space
  • Comma
  • Character

Keep in mind that it only scans 1 letter at a time, for a contiguous sequence of letters, you will need to consume them as chunks.

let text = '[a, [b, [c, e], g], n]';

const parse = (input, bucket=[]) => {
  if (input.length === 0) return bucket;
  let token = input.charAt(0);
  switch (token) {
    case '[':
      let end = input.lastIndexOf(']');
      bucket.push(parse(input.substring(1, end)))
      parse(input.substring(end + 1), bucket);
      break;
    case ' ':
    case ',':
      parse(input.substring(1), bucket);
      break;
    default:
      bucket.push(token);
      parse(input.substring(1), bucket);
  }
  return bucket;
}

console.log(parse(text)[0]) // Unwrap the first item
.as-console-wrapper { top: 0; max-height: 100% !important; }

Post a Comment for "How Convert String Arrays Of Arrays Into Normal Arrays Without Using JSON.parse"