0

I have a name value pair stored as a string that I would like to convert to an object in jQuery or JavaScript. Here is an example of that pair.

{'auto':false, 'itemAWidth':20, 'itemBWidth':20, 'marginLeft':0, 'marginRight':0, 'maximumWidth':0, 'propW':5, 'propX':5, 'propY':null, 'propZ':null}

This is being stored as a string. How can I convert this to a proper object? Some of my unsuccessful attempts appear below.

convertValuePairsToObject = function (pairs) {

  var outObject = {};
  var nodes = pairs.split(',');
  for (var node in nodes) {

  }

  //alert(pairs);
  //return jQuery.parseJSON('"' + pairs + '"');
  //      var outObject = {};
  //      //var nodes = pairs.split(','), dest = outObject;
  //      var  = pairs.split(',');
  //      return outObject;
}

When I attempted to use the jQuery.parseJSON() function, the code returned a very long string that started like this.

{'0':'{', '1':''', '2':'0', '3':''', '4':':', '5':''', '6':'{', '7':''', '8':',', '9':' ', '10':''', '11':'1', '12':''', '13':':', '14':''', '15':''', '16':''', '17':',', '18':' ', '19':''', '20':'2', '21':''', '22':':', '23':''', '24':'a', '25':''', '26':',', '27':' ', '28':''', '29':'3', '30':''', '31':':', '32':''', '33':'u', '34':''', '35':',', '36':' ', '37':''', '38':'4', '39':''', '40':':', '41':''', '42':'t', '43':''', '44':',', '45':' ', '46':''', '47':'5', '48':''', '49':':', '50':''', '51':'o',

=====================================

Edit Below 10:51 AM 1/4/2013

=====================================

So I tried the suggestions you both offered, and have this.

  convertObjectToString = function (obj) {
      return JSON.stringify(obj);
      //      var str = '';
      //      for (var p in obj) {
      //         if (obj.hasOwnProperty(p)) { str += "'" + p + "':" + formatValue(obj[p]) + ", "; }
      //      }
      //      if (str.length > 0) {
      //         str = String(str).substring(0, str.length - 2); // Trim trailing comma
      //         str = '{' + str + '}';
      //      }
      //      return str;
   }

   convertValuePairsToObject = function (pairs) {
      return jQuery.parseJSON('[' + pairs + ']');
   }

But now when convertValuePairsToObject executes, the code pre-pends the name value pairs with this:

{"0":

And if I repeatedly trigger that function, it will keep pre-pending the above to the string, like so:

{"0":{"0":{"0":

I don't need that index identifier of zero. How can I eliminate that?

Sparky
  • 98,165
  • 25
  • 199
  • 285
Ken Palmer
  • 2,355
  • 5
  • 37
  • 57
  • 5
    If you stored the object as a proper JSON string in the first place (hint: you should), then you'd just use `JSON.parse()` to parse it. Splitting on commas like that is going to fail as soon as you've got a value with a comma in it. – Pointy Jan 14 '13 at 16:40
  • http://stackoverflow.com/questions/4375537/convert-json-string-to-array-of-json-objects-in-javascript – Leeish Jan 14 '13 at 16:40
  • Thanks Pointy. The larger context is that I'm trying to preserve some control settings on a page, and am storing them in a hidden text field. I'm able to successfully get the settings into that text field in the needed format. Just getting them back out and reconstituting them as an object is what's stumping me. – Ken Palmer Jan 14 '13 at 16:44
  • 3
    There's no need to store them as a string if you're talking about stuff that's just in one page, but what I'm saying is that you should use `JSON.stringify()` to turn the object into a string, and `JSON.parse()` to convert it back. – Pointy Jan 14 '13 at 16:46
  • Leeish, your solution worked! That was fast. – Ken Palmer Jan 14 '13 at 16:46
  • Pointy, thanks for that. I'll also give that a shot. – Ken Palmer Jan 14 '13 at 16:47
  • Would the settings preservation be an appropriate use for [`.data()`](http://api.jquery.com/data/)? – Bryan Jan 14 '13 at 16:47
  • Thanks everyone, please see the edit that I just posted for the original question. – Ken Palmer Jan 14 '13 at 16:56
  • @KenPalmer Did you read my answer? You need to eliminate the single quotes to make it valid JSON, and then you can use JSON.parse, which is a built in function in the browser. There is no need to use jQuery here. – DigitalZebra Jan 14 '13 at 17:22
  • Oh! I see what you're saying Polaris. Thanks. – Ken Palmer Jan 14 '13 at 17:51
  • @beargle, you are right. Putting that into .data() was a great idea. That made the code even simpler. If I could give all of you a thumbs up, I would. Thank you EVERYONE who responded. – Ken Palmer Jan 14 '13 at 18:10

2 Answers2

3

You need to replace the single quotes with double quotes:

var json = "{'auto':false, 'itemAWidth':20, 'itemBWidth':20, 'marginLeft':0, 'marginRight':0, 'maximumWidth':0, 'propW':5, 'propX':5, 'propY':null, 'propZ':null}".replace(/'/g, '"')

Then, you can use JSON.parse:

JSON.parse(json)
DigitalZebra
  • 39,494
  • 39
  • 114
  • 146
  • Not necessary, thats only for `JSON`. Using `eval` as in the accepted answer shows how it would work with even single quotes – Om Shankar Feb 26 '13 at 16:43
0

assuming you mean that you get the string like this:

"{'auto':false, 'itemAWidth':20, 'itemBWidth':20, 'marginLeft':0, 'marginRight':0, 'maximumWidth':0, 'propW':5, 'propX':5, 'propY':null, 'propZ':null}"

Then one option would be to use eval like this:

var pairs = "{'auto':false, 'itemAWidth':20, 'itemBWidth':20, 'marginLeft':0, 'marginRight':0, 'maximumWidth':0, 'propW':5, 'propX':5, 'propY':null, 'propZ':null}"

var foo = eval("(" + pairs + ")");

foo is now the actual object and not the string.

Executing console.log(foo); will result in the object tree in the debugger not a string.


DEMO - get the object from the string


Alternatively you can convert your object in a string into a proper JSON object and then back into an object using JSON.Parse as mentioned by others.

Nope
  • 22,147
  • 7
  • 47
  • 72
  • Thanks Francois. Below is the code that I ultimately used. This works. convertObjectToString = function (obj) { return JSON.stringify(obj); } convertValuePairsToObject = function (pairs) { return eval("(" + pairs + ")");} – Ken Palmer Jan 14 '13 at 17:44