Convert string to associative array

V

Venkatesh

Hi All,

I have one small doubt regarding associative arrays. Request somebody
to clarify.

Is there a javascript utility function (like split) to convert a
string to associative array? My string is having elements in json
notation - in the form "{'MSRP': 20000, 'cashDown': 2000, 'tradeIn':
1000}"

Thank you,
Venkatesh
 
R

RobG

Hi All,

I have one small doubt regarding associative arrays. Request somebody
to clarify.

Is there a javascript utility function (like split) to convert a
string to associative array? My string is having elements in json
notation - in the form "{'MSRP': 20000, 'cashDown': 2000, 'tradeIn':
1000}"

Javascript doesn't have associative arrays - it has objects with
properties and values, which gives them some features similar to
associative arrays.

What you seem to have is a JSON string, so you can use eval:

var obj = eval("{'MSRP':20000,'cashDown':2000,'tradeIn':1000}");
 
D

Douglas Crockford

Is there a javascript utility function (like split) to convert a
Javascript doesn't have associative arrays - it has objects with
properties and values, which gives them some features similar to
associative arrays.

What you seem to have is a JSON string, so you can use eval:

var obj = eval("{'MSRP':20000,'cashDown':2000,'tradeIn':1000}");

There is a syntactic ambiguity in JavaScript that will cause that to fail.
Failure can be avoided by wrapping the string in parens, so that it will be
interpreted as an expression rather than a block.

var obj = eval('(' +
"{'MSRP': 20000,'cashDown': 2000,'tradeIn': 1000}" + ')');

http://www.JSON.org/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top