0

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?

2
  • Where did this string come from? Commented Oct 29, 2014 at 5:15
  • You should see if you can change the API to provide a correct JSON string (with double quotes, not single quotes). Commented Oct 29, 2014 at 5:46

2 Answers 2

1
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;
}
Sign up to request clarification or add additional context in comments.

12 Comments

the str has empty elements like [,,78,false,,]
@user3331456 replace ,, by ,"",
it can be for example like here [,],[,[,],]
thanks, but it is that only some possible cases. I mean that empty elements can be everywhere in the string. It's just ordinary array with empty elements.
@user3331456 try it with your string. it is possible to make parsing symbol by symbol
|
1

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

1 Comment

the str may contains an empty elements like [['fd',,],false]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.