简体   繁体   中英

Javascript Convert String to Hash

I am having trouble converting a string to a hash (hash with nested hashes actually) in javascript.

I want to convert the following string:

"{'btc_usd': {'price': 376.2, 'volume': 42812.69, 'change': -0.5},'btc_cny': {'price': 2519.39, 'volume': 67148.51, 'change': -85.13},'ltc_usd': {'price': 3.068, 'volume': 4735.55, 'change': -0.58},'btc_ltc': {'price': 0.00805433, 'volume': 153.33, 'change': -0.76},'btc_eth': {'price': 0.00660196, 'volume': 6428.98, 'change': 5.87}}"

I want to make it so that I can do hash['btc_usd']['price'] and get 376.2.

How can I do this?

This is what I have tried but it doesn't seem to be running:

var string="{'btc_usd': {'price': 376.2, 'volume': 42812.69, 'change': -0.5},'btc_cny': {'price': 2519.39, 'volume': 67148.51, 'change': -85.13},'ltc_usd': {'price': 3.068, 'volume': 4735.55, 'change': -0.58},'btc_ltc': {'price': 0.00805433, 'volume': 153.33, 'change': -0.76},'btc_eth': {'price': 0.00660196, 'volume': 6428.98, 'change': 5.87}}"
var results=JSON.parse(string);

The only thing that is different between your string and valid JSON is the usage of single quotes instead of double quotes. So you can just change that, and then parse the resulting JSON.

str = str.replace(/'/g, "\"");
var result = JSON.parse(str);

Of course this is only valid as long as there aren't string literals with single quotes (eg {'name': 'John O\\'hara'} ).

Why don't you use the JSON directly?

var string = "{'btc_usd': {'price': 376.2, 'volume': 42812.69, 'change': -0.5},'btc_cny': {'price': 2519.39, 'volume': 67148.51, 'change': -85.13},'ltc_usd': {'price': 3.068, 'volume': 4735.55, 'change': -0.58},'btc_ltc': {'price': 0.00805433, 'volume': 153.33, 'change': -0.76},'btc_eth': {'price': 0.00660196, 'volume': 6428.98, 'change': 5.87}}";
string = "hash = " + string + ";";
eval(string);

console.log(hash.btc_usd.price);

It is very simple but it comes with a price-tag: the eval() is dangerous if you do not know exactly where your string comes from, eg: you didn't produce it yourself. It is also expensive: if you want to use it in a loop over some thousand or more entries you'll see some time passing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM