-2

I have an array of objects which is a string.

       [{
          'version_name': '1.4',
          'url': 'url'
        },
        {
         'version_name': '1.3',
          'url': 'url'
        },
        {
          'version_name': '1.2',
          'url': 'url'
        },
        {
          'version_name': '1.1',
          'url': 'url'
        }]

I am using this code to remove all the space:

str = str.replace(/\s+/g, '');

Now, I want to convert it to proper array of objects. How do i do that? I tried string.split() which kind of works but each array element becomes a string instead of an object.

prisoner_of_azkaban
  • 700
  • 1
  • 8
  • 26

3 Answers3

3

If you control the source of the string, the best thing would be to modify the source so that it creates valid JSON (" instead of ' on property keys and strings).

If you can't change the source of it and have to deal with that string, you have a couple of options:

Replace the ' with " and use JSON.parse, since that text is valid JSON other than that it uses ' instead of " and it doesn't appear to use ' for anything else:

var result = JSON.parse(theText.replace(/'/g, '"'));

Live Example:

var theText = "[{'version_name':'1.1','url':'value'}, {'version_name':'1.2','url':'value'}, {'version_name':'1.32','url':'value'}, {'version_name':'1.4','url':'value'}]";
var result = JSON.parse(theText.replace(/'/g, '"'));
console.log(result);

Your other option, if you trust the source of that text, is to use eval, since the quoted text is valid JavaScript object initializer syntax.

// ONLY IF YOU CAN ABSOLUTELY TRUST THE SOURCE OF THAT TEXT
var result = eval(theText);

Live Example:

var theText = "[{'version_name':'1.1','url':'value'}, {'version_name':'1.2','url':'value'}, {'version_name':'1.32','url':'value'}, {'version_name':'1.4','url':'value'}]";
var result = eval(theText);
console.log(result);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I had answered it long back but unable to find it. But single quote can be a part of value. You cannot do this in 1 go. My suggestion: **1.** `str.replace(/\':\'/g, '":"')`. **2.** `str.replace(/{'/g, '{"')`. **3.** `str.replace(/'}/g, '"}')` – Rajesh Sep 11 '17 at 09:41
  • @Rajesh: That's why I said *"...and it doesn't appear to use ' for anything else..."* – T.J. Crowder Sep 11 '17 at 09:42
  • Also, I guess we should add a caveat for *eval is evil*. – Rajesh Sep 11 '17 at 09:50
  • @Rajesh: Again, that's there too, though not so simplistically. – T.J. Crowder Sep 11 '17 at 09:54
  • Yup I noticed *trust the source of that text,* but eval will have context performance issues and its a bad practice. Hence I pointed it out. But its just a suggestion – Rajesh Sep 11 '17 at 09:57
  • @Rajesh: Claims that `eval` is slow are dramatically overstated by the "`eval` is evil" brigade. Not only is `eval` of comparable performance to `JSON.parse`, but sometimes it's faster: https://jsperf.com/is-eval-really-slow (I really should have separated the obj vs. arr tests into separate ones, but I can't be bothered now :-) ). Solve performance problems when you have performance problems. 10% either way on converting text to objects isn't going to be the source of a performance issue. When it's the right tool, which is very rarely, `eval` is just fine. – T.J. Crowder Sep 11 '17 at 10:11
0

A JSON string expects key and value to be wrapped in double quotes and not in single. But replacing every single quote can be incorrect as it can be a part of value. So you can pass string through series of regex to make it in correct format.

Sample:

var str = "[{'invalid_value': 'foo's','version_name': '1.4','url': 'url'} , {'version_name': '1.3','url': 'url'},{'version_name': '1.2','url': 'url'},{'version_name': '1.1','url': 'url' }]";

function parseObj(str) {
  str = str.replace(/\'\s*:\s*\'/g, '":"');
  str = str.replace(/\'\s*,\s*'/g, '","');
  str = str.replace(/{\s*\'/g, '{"');
  str = str.replace(/\'\s*}/g, '"\}');
  return JSON.parse(str);
}

console.log(parseObj(str))
Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • 1
    The above makes lots of assumptions about the string, such as that there's no whitespace between the `'` and the `:` when it's a key, that there's no whitespace on either side of the `,` when that `,` is between entries, that there's no whitespace between `{` and `'` when that's the start of an object, that there are no `"` in actual string values, ... Since this makes so many assumptions, it seems reasonable to only assume what we need from the actual quoted string in the OP's question. In which case, it can be a **lot** simpler. – T.J. Crowder Sep 11 '17 at 09:57
  • @T.J.Crowder True. Also thanks for pointing space mistake. Have updated it. Hope now it serves better. – Rajesh Sep 11 '17 at 10:20
-2

you can use json parse: const arr = JSON.parse(yourString.replace(/'/g, '"')))

mbehzad
  • 3,758
  • 3
  • 22
  • 29