assigning a item from a .json file to a variable in javascript - javascript

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.

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 of JSON.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

Related

How to read JSON Response from URL and use the keys and values inside Javascript (array inside array)

My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});

Get object from JSON with jQuery

I'm trying to query a JSON file in my own server using $.getJSON and then cycling inside the objects. No problem so far, then i have an ID which is the name of the object i want to return, but can't seem to get it right:
var id = 301;
var url = "path/to/file.json";
$.getJSON( url, function( json ) {
var items = [];
items = json;
for (var i = 0; i < items.length; i++) {
var item = items[i];
console.log(item);
}
});
This prints the following in the console:
Now let's say i want return only the object == to id so then i can refer to it like item.banos, item.dorms etc.
My first approach was something like
console.log(json.Object.key('301'));
Which didn't work
Any help would be very much appreciated.
It seems like your response is wrapped in an array with one element.
You can access object properties dynamically via square brackets:
var id = 301;
var url = "path/to/file.json";
$.getJSON(url, function(json) {
console.log(json[0][id].banos);
});
As you have the name of the property in the object you want to retrieve you can use bracket notation. you can also simplify your code because of this:
var id = 301;
//$.getJSON("path/to/file.json", function(json) {
// response data from AJAX request:
var json = {
'301': {
banos: 2
},
'302': {
banos: 3
},
'303': {
banos: 4
},
'304': {
banos: 5
},
};
var item = json[id];
console.log(item);
//});
$.each(items,function(n,value){
if(n==301)
alert(value);
});

How to use data outside of function returned from POST or GET method of jquery?

How to use data outside of function returned from POST or GET method of jquery?
My question is i'm getting some data through jquery post method.. the problem is whenever i get data i'm just able to use that within function actually i want that data to use outside of function.. as i alerted data outside function it's not working...
function getlatlanfromjs() {
$(document).ready(function() {
var uid = $(".track_textbox").val();
$.post("getLatLan.php", {userid: uid}, function(data) {
var i;
for (i = 1; i < 2; i++) {
initialize(data[i]["latitude"], data[i]["longitude"]);
}
}, "json");
alert(data[1]["latitude"]); //this is actually not alerting.. what is the reason ?
});
}
Because data variable is out of scope at that point. Code below will assign the data to the local recievedData and you can use it out of the handling function scope. Though you will still be only able to access recievedData variable only when request is done.
$(document).ready(function() {
var recievedData;
var uid = $(".track_textbox").val();
var promise = $.post("getLatLan.php", {userid: uid}, function(data) {
recievedData = data;
var i;
for (i = 1; i < 2; i++) {
initialize(data[i]["latitude"], data[i]["longitude"]);
}
}, "json");
promise.done(function() {
alert(recievedData[1]["latitude"]); });
});
this is a bit better...
This way you dont miss the execution. If you wrap your code into a closure, you can call it later too. So even though your "getlatlanfromjs" has already executed, your alertFn still exists and will be called when the $.post is done.
function getlatlanfromjs() {
$(document).ready(function() {
var uid = $(".track_textbox").val();
var alertFn = function(data) { alert(data[1]["latitude"]); };
$.post("getLatLan.php", {userid: uid}, function(data) {
var i;
for (i = 1; i < 2; i++) {
initialize(data[i]["latitude"], data[i]["longitude"]);
}
alertFn(data);
}, "json");
}); }
var mydata = null;
function getlatlanfromjs() {
$(document).ready(function() {
var uid = $(".track_textbox").val();
$.post("getLatLan.php", {userid: uid}, function(data) {
mydata = data;
var i;
for (i = 1; i < 2; i++) {
initialize(data[i]["latitude"], data[i]["longitude"]);
}
}, "json");
if(mydata != null) alert(data[1]["latitude"]);
});
}
All you needed to do was keep track of the scope of data.

retrieve value in unnamed json array url

I'm struggling to retrieve some value on a json in this url:
http://go-gadget.googlecode.com/svn/trunk/test.json
the url data looks like this:
[
{
"key":{
"parentKey":{
"kind":"user",
"id":0,
"name":"test 1"
},
"kind":"smsgateway",
"id":5707702298738688
},
"propertyMap":{
"content":"test1 content",
"date":"Dec 12, 2013 2:58:57 PM",
"user":"test1"
}
}]
By ignoring the "key", I want to access the value of "propertyMap" object (content,date and user) using javascript code.
I have tried this code but it couldn't get the result:
var url = "http://go-gadget.googlecode.com/svn/trunk/test.json";
$.getJSON(url, function (json) {
for (var i = 0; i < json.length; i = i + 1) {
var content = json[i].propertyMap.content;
console.log('content : ', content);
var user = json[i].propertyMap.user;
console.log('user: ', user);
var date = json[i].propertyMap.date;
console.log('date : ', date);
}
});
(unsuccessful code here http://jsfiddle.net/KkWdN/)
considering this json can't be change, is there any mistake I've made from the code above or there's any other technique to get the result?
I just learn to use javascript and json for 1 month so response with an example is really appreciated.
--edited: I change [].length to json.length, now I'm looking for the answer to access the url
That would be something like :
$.getJSON("http://go-gadget.googlecode.com/svn/trunk/test.json", function(json) {
for (var i = 0; i < json.length; i++) {
var map = json[i].propertyMap;
var content = map.content;
var user = map.user;
var date = map.date;
$('#date').text(date);
$('#nohp').text(user);
$('#content').text(content);
}
});
But the request fails, as no 'Access-Control-Allow-Origin' header is present on the requested resource, so you're being stopped by the same origin policy
What do you think [].length; would evaluate to .
It is 0 , so it would never go inside the for loop.
Other than that you code looks ok.
Replace your for loop as below
$.getJSON(url, function (json) {
for (var i = 0; i < json.length; i = i + 1) {
Also you seem to be accessing a API as part of the different domain.
So you need to use CORS or JSONP to get this working if you want to retrieve data from a different domain.
Change:
for (var i = 0; i < [].length; i = i + 1) {
to
for (var i = 0; i < json.length; i = i + 1) {
DEMO here.
How about using something like the following
In your case, say the object is myObj, I would get the value like this
var content = fetchValue(myObj, [0, "propertyMap", "content"], "");
var date = fetchValue(myObj, [0, "propertyMap", "date"], new Date());
var user = fetchValue(myObj, [0, "propertyMap", "user"], "");
Just to make sure that we send a default value in case we do not get the desired ojbect. The beauty of this approach is that now you do not have to worry about array or objects nested in the structure. The fetchValue function could be something like below.
function fetchValue(object, propertyChain, defaultValue){
var returnValue;
try{
returnValue = object;
forEach(propertyChain, function(element){
returnValue = returnValue[element];
});
}catch(err){
return defaultValue;
}
if(returnValue == undefined) {
returnValue = defaultValue;
}
return returnValue;
}
Adding the forEach function
function forEach(array, action){
for(var x in array)
action(array[x]);
}

Using Javascript with php

I know this question has already been asked a few times, but I'm trying to use javascript with php. I have a file called parsing.php that parses through a xml feed and converts the metadata into JSON Object called "data". The parsing is done using ajax calls with JavaScript and JQuery.
<script src="json2.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
$.ajax({
type: 'GET',
url: 'fakeFeed.xml',
dataType: 'xml',
async: false,
success: function(data, textStatus, jqXHR) {
function getRandom(max) {
return Math.floor(Math.random() * max);
}
function getThumbId(small) {
var num = getRandom(15);
if (num == 0) {
num = 1;
}
if (num < 10) {
num = '0' + num;
}
return num.toString();
}
var categories = new Array(); // Array for the categories
var category = {
name : '',
videos: []
};
var data1 = data;
var data = {
categories: []
};
$(data1).find('item').each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
for (var j = 0; j<5; j++) {
var video = {
sources: [el.find('media\\:content, content').attr('url')],
thumb : 'images\/thumbs\/thumb' + getThumbId() + '.jpg',
title : el.find("title").text(),
subtitle : el.find("description").text(),
description: ""
}
category.videos.push(video);
}
data.categories.push(category);
}
});
window.data = JSON.stringify(data);
<script>
"<?php
$dataVar = ?> <script type=text/javascript>window.data</script><?php;?>"
"<?php
print_r($dataVar,true);
?>"
The only reason why I need to use javascript and php is because I want to use the "print_r()" function from php which allows me to return the information rather than just printing it to the screen, but unfortunately I can't get it to work. If anybody knows of other alternative or could give some advice that would be greatly appreciated.
Here is what I believe you are trying to achieve, written in PHP:
$dom = new DOMDocument();
$dom->load("fakeFeed.xml");
$data = ["categories"=>[]]; // may need to use array() instead of [] depending on PHP version
foreach($dom->getElementsByTagName('item') as $item) {
$name = trim($item->getElementsByTagName('category')->item(0)->textContent);
if( !isset($data['categories'][$name])) {
$cat = ["name"=>$name,"videos"=>[]]; // again, adjust if you're on an older version
// I'm not entirely sure what you're trying to achieve on this part.
// you seem to be getting the same video five times...
// revise your approach, comment if needed, and I can try to help
// for now, "insert code here"
$data['categories'][$name] = $cat;
}
}
// we were using the name as a key for simplicity, now just take the values
$data['categories'] = array_values($data['categories']);
// done! $data now has your data.
var_dump($data);
If you really want to use this instead of using document.log for JS:
$.ajax({
type: "POST",
url: "some_php.php",
data: JSON.stringify(data);
})
.done(function( msg ) {
document.write(msg);
});
and the some_php.php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

Categories

Resources