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?
assuming you mean that you get the string like this:
Then one option would be to use
evallike this:foois 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.Parseas mentioned by others.