2

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)

tdub2012
  • 103
  • 2
  • 8
  • Why not send the string as JSON and use `JSON.parse( string )` – elclanrs Dec 25 '12 at 02:14
  • Why would you store data like that in a database? – Musa Dec 25 '12 at 02:14
  • I have an array of these objects basically and that is how it is being stored. – tdub2012 Dec 25 '12 at 02:20
  • I don't think it's worth your time finding a solution for this problem, because the problem is actually your string format, using JSON is IMO the proper solution here, instead of trying to parse a format that you created which btw looks very similar to JSON -> `var string = '{"name": "bob", "height": 4, "weight": 145}'` – elclanrs Dec 25 '12 at 02:26
  • ok, thankyou, I am still learning and I am not very familiar with JSON, however, I get what you are saying and will switch to that as it seems the easiest. thankyou. – tdub2012 Dec 25 '12 at 02:31

3 Answers3

3

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?

Community
  • 1
  • 1
Chris Simpson
  • 7,821
  • 10
  • 48
  • 68
1

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.

Igor
  • 15,833
  • 1
  • 27
  • 32
1

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.

Jasdeep Khalsa
  • 6,740
  • 8
  • 38
  • 58