tdub2012
tdub2012

Reputation: 103

String to Object

So basically I have this code:

var string = '{name: "bob", height: 4, weight: 145}';

I would like to know if it is possible to convert that string into an object. so that I can use

string.name, string.height, and string.weight

(I am retrieving the string variable from a database so I cannot just remove the quotes and make it an object in the first place)

Upvotes: 2

Views: 107

Answers (3)

Jasdeep Khalsa
Jasdeep Khalsa

Reputation: 6919

It seems that your string is malformed. In order to work with JSON.parse or even jQuery.parseJSON methods, your keys must have speech marks (" ) around them, like so:

var str = '{"name": "bob", "height": 4, "weight": 145}';
var obj = JSON.parse(str);

You can test this by adding console.log(obj);​ as the final line. Here is my jsFiddle example.

So try to see if you can pull down the data from the server in the format I have suggested and it can then easily be parsed into a JavaScript object.

Upvotes: 1

Igor
Igor

Reputation: 15893

I would not use string for a variable name, but:

var obj = eval(string);
alert(obj.name);

or you can use jQuery.parseJSON: api.jquery.com/jQuery.parseJSON.

Upvotes: 1

Chris Simpson
Chris Simpson

Reputation: 7990

eval, as suggested by Igor, will certainly work but is vulnerable to attack.

Instead you could use a library to parse it for you. There are options in the following link:

Eval is evil... So what should I use instead?

Upvotes: 3

Related Questions