I’m trying to get Jquery to read a json file,
But unfortunately I can not get it to work.
This is my json file. see: http://bitcoincharts.com/t/weighted_prices.json
{
"USD": {"7d": "4.4549", "30d": "5.2016", "24h": "4.1373"},
"GBP": {"7d": "2.9706", "30d": "3.2620", "24h": "2.5463"},
}
My jquery script looks like this
<script type="text/javascript">
(document).ready(function(){
$.getJSON('http://bitcoincharts.com/t/weighted_prices.json',function(data){
$("#results").html(data[0].30d);
});
});
</script>
I try to grab USD>30d>5.2016
To get USD -> 30d (= 5.2016) you need to do this:
You can’t say
data[0]because using a numeric index is (generally) only applicable to arrays and you don’t have an array. You have an object with two properties, “USD” and “GBP”, and each of those properties has an object with the properties “7D”, “30d”, “24h”.In more detail:
JavaScript array literal declarations use square brackets that contain simply a list of elements, like this:
But object literal declarations use curly brackets with key-value pairs like in the JSON you provided in your question, or here’s a simpler example:
The “trick” is that once defined both arrays and objects are accessed with the square bracket notation, but arrays use numeric indexes and objects use string keys.
You can also use dot notation like you were trying to do, but only on properties with a key name that meets the rules of valid JavaScript identifiers, i.e., not starting with a number, no spaces, not a reserved word, etc. These restrictions only apply to dot notation though, so if you use the square bracket notation you can have spaces, numbers, etc.
It’s fine to nest arrays and objects, including mixing the two, but in your particular case you just had an object containing two other objects, no arrays.
So
data["USD"]will give you{"7d": "4.4549", "30d": "5.2016", "24h": "4.1373"}.data["GBP"]will give you{"7d": "2.9706", "30d": "3.2620", "24h": "2.5463"}.You narrow it down to the individual value you want with
data["USD"]["30d"].EDIT: Your
$.getJSONrequest isn’t going to work because of the Ajax same-origin policy, i.e., you are only allowed to make JSON requests to the same domain as the current page’s.You could try JSONP – which jQuery supports with practically no effort on your part: you just have to add
?callback=?to the end of the url – except that JSONP requires support on the server and it looks like the bitcoin people don’t support it.So the easiest way forward is to get the data in your server side code where the same-origin policy won’t get in your way.