471,120 Members | 1,299 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,120 software developers and data experts.

Convert string to associative array

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

Feb 16 '07 #1
2 25647
On Feb 16, 4:57 pm, "Venkatesh" <venkatbab...@gmail.comwrote:
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 }");

--
Rob

Feb 16 '07 #2
>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 }");
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/
Feb 16 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Robert Oschler | last post: by
27 posts views Thread by Abdullah Kauchali | last post: by
6 posts views Thread by mark4asp | last post: by
8 posts views Thread by Derek Basch | last post: by
41 posts views Thread by Rene Nyffenegger | last post: by
11 posts views Thread by Bosconian | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.