1

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! I did use 'order' before. This was just hastily rewritten for stackoverflow. I didn't downvote? I'm waiting till the time limit passes so I can tick.
1

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.

6 Comments

No, the easiest way to deal with a JSON string is to use JSON.parse. You should not need to use eval for this.
Using eval is generally a bad idea. Try to avoid that if possible.
Omg i know it but it is works too. If i write this method that it doenst mean that i use it
@DenisErmolin - Then why promote bad practice?
I didnt promote bad practice. I comented that your way is safer to use. He must know all possible methods and bad too.
|
1

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");

2 Comments

Why you are using "text" instead of "json" ?
That's a really good question, Denis. I started using 'text' to avoid the need for 'intelligent guess' and because I guess the model I used initially also used 'text'. I'm not sure what the practical difference would be if I made it 'json'. My initial impression is that it might remove the need for the parse step. Thwt's how the second last example appears on api.jquery.com/jQuery.post. I might need to update a heap of code! It works fine as I posted, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.