简体   繁体   中英

String with arrays to array

I have that string:

str = "['movies', ['The Wind', [7, 'acters', ['Any', 'Roberto']]],['Abc',['acters',['Max', 'Alex', 0.312, false, true]]]]"

As you noticed the str has numbers and true/false values without quotes.

is there a easy way to convert it in a correct array?

arr = strToArr(str)
arr[1][0][1] // 'Alex'

UPD. And the str has empty elements like [,,,] or like here [,],[,[,],].

UPD2. Empty elements can be everywhere in the string. It's just ordinary array with empty elements.

UPD3. Well. I can use eval(str) and after I can work with it like with array. But is it the only way to do it easy?

var str = ("['movies', ['The Wind', [7, 'acters', ['Any', 'Roberto']]]," + 
       "['Abc',['acters',['Max', 'Alex', 0.312, false, true]]]]").replace(/'/g, '"');

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

Replace ' with " and parse as json string.

ps: I broke it into two lines just for better readability.

pps: if you have something like [, , ,] or ,, replace .replace part with .replace(/'/g, '"').replace(/([\\[,])\\s*([\\],])/g, '$1 "" $2');

ppps: ok, this is for your weird case

var str = "['movies', ['The Wind', [7, 'acters', ['Any', 'Roberto']]]," + 
         "['Abc',['acters',['Max', 'Alex', 0.312,, false, true,],[,],[,[,],]]]]";

str = fixJson(str.replace(/'/g, '"'));
console.log(JSON.parse(str));

function fixJson(match, m1, m2, m3) {
   if (m1 && m2)
        match = m1 + '""' + m2 + (m3 ? m3 : '');
   return match.replace(/([\[,])\s*([\],])([\s\]\[,]+)?/g, fixJson);   
}

pps#?: I wrote a symbol by symbol parser, but it is not complete: 1) it does not check the closure, but you can count number of [ and ] 2) ... probably something else ... like it trims all quotes, but can be fixed by modification of /^["'\\s]+|["'\\s]+$/g to /^\\s*'|'\\s*$/g , for example.

var str = "['movies', ['The Wind', [7, 'acters', ['Any', 'Roberto']]]," + 
     "['Abc',['acters',['Max', 'Alex', 0.312,, false, true,],[,],[,[,],]]],]";

var result = parse(str, 0);
console.log(result);

function parse(str, start)
{
   var i = start, res = new Array(), buffer = '',
       re = /^\s*'|'\s*$/g, quotes = false;

   while(i < str.length) {  // move along the string
       var s = str[i];
       switch(s) {          // check the letter
           case "'":   // if quote is found, set the flag inside of element
             if (buffer.substr(-1) != '\\') // check for escaping
                quotes = !quotes;
             else
                buffer = buffer.substring(0, buffer.length - 1); // remove /
             buffer += s; 
           break;

           case '[':        // opening [ 
              if (!quotes) {   // not inside of a string element
                 ret = parse(str, i + 1); // create subarray recursively
                 i = ret.pos;   // get updated position in the string
                 buffer = null;
                 res.push(ret.ret); // push subarray to results
              } else buffer += s;   // add symbol if inside of a string
           break;

           case ']':               // closing ]
              if (!quotes) {       // not inside of a string
                 if (buffer != null)  // buffer is not empty
                    res.push(buffer.replace(re, "")); // push it to subarray
                 return {ret: res, pos: i}; // return subarray, update position
              }
              buffer += s;  // if inside of a string - add letter
           break;

           case ',':               // comma
              if (!quotes) {       // not inside of a string
                if (buffer != null) // buffer is not empty
                  res.push(buffer.replace(re, "")); // push it to results
                buffer = '';       // clear buffer
                break;
              }

           default: buffer += s; break;  // add current letter to buffer
       }
       i++;
   }
   return res;
}

If you swap your quotes single to double, double to single like this:

var str = '["movies", ["The Wind", [7, "acters", ["Any", "Roberto"]]],["Abc",["acters",["Max", "Alex", 0.312, false, true]]]]'

Then you could use a JSON parse method ( JSON.parse in some native implementations)

var arr = JSON.parse(str);
console.log(arr[1][1][0]); //=> 7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM