简体   繁体   中英

JSON mapping in Javascript

So I have this JSON

https://bitcoinpayflow.com/orders{"order":{"bitcoin_address":"1NwKSH1DJHhobCeuwxNqdMjK5oVEZBFWbk"}}

No I want to reference the bitcoin_address

So first I strip away the string at the beginning

        var stripped = data.substring(33);
        alert(stripped);
                var btc = stripped.orders.bitcoin_address;
        alert(btc); 

I get the first alert, but not the second. Any idea why?

Because stripped is still just a string. You need to parse it into an object. You can use the native JSON.parse method to do this:

var stripped = JSON.parse(data.substring(33));

Also, you are referencing the orders property, which doesn't exist. It's order .

Note that JSON.parse is not supported by older browsers. You can use this polyfill to make sure it's always available.

The easiest way to decode json - string - use eval

var bitcoins = eval('(' + json_string + ')');

And access bitcoins['order']['bitcoin_address'] But it a bit unsafe. Upper method is more safer.

I would use JSON.parse as follows.

$.post('php/whatever.php',{data:dS},function(res){
    var o=JSON.parse(res);
    var bitcoins=o.order.bitcoinaddress;
},"text");

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