assigning a item from a .json file to a variable in javascript
Assuming you've read your json file into a javascript JSON object (do you need help with that as well?)
var R1 = new Array(); for(var i= 0 ; i< myJSON.length; i++){ R1.push(myJSON[i].BID);}
[EDIT]
Your document.write is happening before you've done any reading.
Remove it.
put a console.log instead in your anonymous callback from your $.get();
Make it look like this:
$.get('data1.json', function (data) { var parsedArr = JSON.parse(data), for (i = 0; i < parsedArr.length; i++) { R1.push(parsedArr[i].BID); } for(i=0; i< R1.length; i++) console.log("item " + i + " = " + R1[i]);});
Also if your json file really looks like this:
[ { "BID" : "4569749", }, { "BID" : "466759", }, { "BID" : "4561149", }, ]
Then it needs to be fixed to remove the extraneous commas inside your objects. It should look like this:
[ { "BID" : "4569749" }, { "BID" : "466759" }, { "BID" : "4561149" } ]
I haven't tested this, but it looks like it should work to me.
var R1 = [];$.get('file.json', function (data) { var parsedArr = JSON.parse(data), i = 0, l = parsedArr.length; for (i; i < l; i++) { R1.push(parsedArr[i].BID); }});
Getting the json file with ajax, then process it and assign to R1:
function ajaxGetJson(url, callback){ var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { callback(eval(xmlhttp.responseText)); } } xmlhttp.open("GET", url, true); xmlhttp.send();}var R1;ajaxGetJson('file.json', function(obj){ R1 = obj.map(function(item){ return item.BID });});
Some comments:
I'm using
eval
instead ofJSON.parse
because your .json may not be in strict json format (as your example)As the question has tag
html5
, your browser for sure supports the.map
method
Cheers, from La Paz, Bolivia