I have a data1.json file
[ { "BID" : "4569749", }, { "BID" : "466759", }, { "BID" : "4561149", }, ]
I want to call this .json file inside another abdv.js file and assign the BIDs to a variable array
var R1;
i.e the value of R1 = ['4569749', '466759', '4561149']
How can i do this??
.html file(please note: I am specifying only those parts relevant to this quetsion and erased other parts)
Code follows:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="abdv.js"></script>
<script>
loadABCD();
</script>
abvd.js
Code follows:
function loadABCD()
{
var R1 = [];
$.get('data1.json', function (data) {
var parsedArr = JSON.parse(data),
i = 0, l = parsedArr.length;
for (i; i < l; i++) {
R1.push(parsedArr[i].BID);
}
});
for(k=0;k<R1.length;k++)
{
document.write(R1);
}
// i will use R1 for later processing another function
// for(k=0; k<R1.length; k++)
// {
// obj = loadLevel4Obj(R1[k]);
// scene.add(obj);
// }
}
I also need help to read .json file into a javascript JSON object. I doubt whether the format of my json file is correct. Do i need to specify any other jquery related libs in the html file?? How do i check whether the BIDs are correctly stored in the variable R1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With