0

I'm reading Object initializer strings from a database but can't see any easy way to turn them back into objects.

For example, given the following string, how would you turn it into an object?

var initializer = "{type: car, colour: red, engine: 2.0L}";

I ended up decoding them by just looping through piece by piece but felt that there must be a better way.

Galadai
  • 77
  • 6
  • 2
    You want to fix the format coming from the DB. Use JSON. – elclanrs Aug 23 '14 at 19:31
  • Looks almost like JSON, but isn't quite. It looks exactly like that coming from the DB? – Brennan Aug 23 '14 at 19:32
  • 1
    Duplicate of http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript – Ankit Ladhania Aug 23 '14 at 19:36
  • As long as your string is not a valid dataformat, like JSON, the only way to create an object is to do it yourself by iterating or in some other way parsing the string. There are no built in parsers for the format you're returning, but as noted, it's close to JSON, which is probably what you should be returning. – adeneo Aug 23 '14 at 19:38

2 Answers2

0

In the unlikely case that, instead of returning JSON from the server as you should, you do end up parsing this yourself, here's how you might do that:

initializer
  .replace(/^\{|\}$/g, '')            // remove {} at beginning and end
  .split(',')                         // break apart into key: val pairs
  .reduce(function(result, keyval) {  // build object 
    var parts = keyval.split(':').map(''.trim);
    result[parts[0]] = parts[1];
    return result;
  }, {});

Of course, you'd probably want to add a bunch of bullet-proofing to that.

If you're using Underscore, you could use its ability to create an object from an array of [key, val] pairs:

_.object(initializer
  .replace((/^\{|\}$/g, '')
  .split(',')
  .map(function(keyval) {
    return keyval.split(':').map(''.trim);
  })
);
0

since your data isn't quoted there won't be a difference between datatypes everything must be parsed as string.

Instead of trying to parse this shit i would try to create valid parsable data in the first place.

King Loui
  • 190
  • 9