getting json data from tree and feeding through to associative array - javascript

I'm trying to read a JSON API and parse the data into an associative array but I can't seem to get it to work. I must be doing something wrong.
Here is my code:
var matchedValues = {};
$.getJSON(url ,function(data) {
$.each(data, function() {
var value = this["value"];
var climb = this["climb"];
matchedValues[value] = climb;
});
});
console.log(matchedValues); //Outputs Object{}
Any ideas? I don't think I am console logging it correctly or maybe I'm doing something wrong?
Thanks

matchedValues is an Object not an array. try something likmatchedValues['your_key'] to get the value.

I assume that the data coming back from the ajax call is a JSON string, which you wish to parse. If that’s the case, then the problem is already solved using JavaScript’s JSON object:
var matchedValues = {};
$.getJSON(url ,function(data) {
matchedValues=JSON.parse(data);
});
console.log(JSON.stringfy(matchedValues)); //Outputs Object{}
As you see in the above example, you have to reverse the process in order to print it out.
See JSON MDN Article

Try this approach from jquery documentation
EDIT:
$.getJSON(url, function(data) {
var matchedValues = {};
$.each(data, function(key, val) {
items[key] = val;
});

If I understood your question, then your data is an Array of objects, and you want to consolidate them in a big object.
If got it right, then use this approach:
var matchedValues = {};
$.getJSON("ajax/test.json", function(data) {
for (var i = 0; i < data.length; i++) {
for (key in data[i]) {
matchedValues[key] = data[i][key];
}
}
console.log(matchedValues); //this should print your object.
});
The data objects must have different keys or they will be overlapsed.

Related

how can i filtering data from Firebase rt-db using javascript

I need to print in console value of key temp but no things displayed
var database=firebase.database();
var ratingRef = firebase.database().ref("sensors/temp/");
ratingRef.orderByValue().on("value", function(data) {
data.forEach(function(data) {
console.log( data.val());
});
});
There's no need for using orderByValue. You have direct reference to the temp child so the data (which is a DataSnapshot) contain the value of temp only.
var ratingRef = firebase.database().ref("sensors/temp");
ratingRef.on("value", function(data) {
console.log(`Temp: ${data.val()}`)
});

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

Reading unlabelled JSON arrays

I am trying to pull data, using JQuery, out of an unlabelled array of unlabelled objects (each containing 4 types of data) from a JSON api feed. I want to pull data from the first or second object only. The source of my data is Vircurex crypto-currency exchange.
https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC
By 'unlabelled' I mean of this format (objects without names):
[{"date":1392775971,"tid":1491604,"amount":"0.00710742","price":"40.0534"},{ .... }]
My Javascript look like this:
var turl = 'https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC';
$.getJSON(turl, function (data) {
$.each(data, function(key,obj) {
var ticker1tid = obj[1].tid;
var ticker1amount = obj[1].amount;
var ticker1date = obj[1].date;
var ticker1price = obj[1].price;
});
});
Somehow I am not calling in any data using this. Here is link to my sand-box in JSFiddle: http://jsfiddle.net/s85ER/2/
If you just need the second element in the array, remove the traversing and access it directly from the data:
var turl = 'https://api.vircurex.com/api/trades.json?base=BTC&alt=LTC';
$.getJSON(turl, function (data) {
var ticker1tid = data[1].tid;
var ticker1amount = data[1].amount;
var ticker1date = data[1].date;
var ticker1price = data[1].price;
// Or isn't it better to just have this object?
var ticker = data[1];
ticker.tid // 1491736
ticker.amount // 0.01536367
// etc
});

Convert javascript object or array to json for ajax data

So I'm creating an array with element information. I loop through all elements and save the index. For some reason I cannot convert this array to a json object!
This is my array loop:
var display = Array();
$('.thread_child').each(function(index, value){
display[index]="none";
if($(this).is(":visible")){
display[index]="block";
}
});
I try to turn it into a JSON object by:
data = JSON.stringify(display);
It doesn't seem to send the proper JSON format!
If I hand code it like this, it works and sends information:
data = {"0":"none","1":"block","2":"none","3":"block","4":"block","5":"block","6":"block","7":"block","8":"block","9":"block","10":"block","11":"block","12":"block","13":"block","14":"block","15":"block","16":"block","17":"block","18":"block","19":"block"};
When I do an alert on the JSON.stringify object it looks the same as the hand coded one. But it doesn't work.
I'm going crazy trying to solve this! What am I missing here? What's the best way to send this information to get the hand coded format?
I am using this ajax method to send data:
$.ajax({
dataType: "json",
data:data,
url: "myfile.php",
cache: false,
method: 'GET',
success: function(rsp) {
alert(JSON.stringify(rsp));
var Content = rsp;
var Template = render('tsk_lst');
var HTML = Template({ Content : Content });
$( "#task_lists" ).html( HTML );
}
});
Using GET method because I'm displaying information (not updating or inserting). Only sending display info to my php file.
END SOLUTION
var display = {};
$('.thread_child').each(function(index, value){
display[index]="none";
if($(this).is(":visible")){
display[index]="block";
}
});
$.ajax({
dataType: "json",
data: display,
url: "myfile.php",
cache: false,
method: 'GET',
success: function(rsp) {
alert(JSON.stringify(rsp));
var Content = rsp;
var Template = render('tsk_lst');
var HTML = Template({ Content : Content });
$( "#task_lists" ).html( HTML );
}
});
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
}
To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:
// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
return oldJSONStringify(convArrToObj(input));
};
})();
And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)
Edit:
Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
jsFiddle with example here
js Performance test here, via jsPerf

How get parametrs from json?

Full code:
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
});
in data i get json:
{
"server":9458,
"photo":
"[{\"photo\":\"0d6a293fad:x\",\"sizes\":
[[\"s\",\"9458927\",\"1cb7\",\"PX_xDNKIyYY\",75,64],
[\"m\",\"9458927\",\"1cb8\",\"GvDZr0Mg5zs\",130,111],
[\"x\",\"9458927\",\"1cb9\",\"sRb1abTcecY\",420,360],
[\"o\",\"9458927\",\"1cba\",\"J0WLr9heJ64\",130,111],
[\"p\",\"9458927\",\"1cbb\",\"yb3kCdI-Mlw\",200,171],
[\"q\",\"9458927\",\"1cbc\",\"XiS0fMy-QqI\",320,274],
[\"r\",\"9458927\",\"1cbd\",\"pU4VFIPRU0k\",420,360]],
\"kid\":\"7bf1820e725a4a9baea4db56472d76b4\"}]",
"hash":"f030356e0d096078dfe11b706289b80a"
}
I would like get parametrs server and photo[photo]
for this i use:
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
but in concole i get undefined
Than i use code:
var Server = data.response.server;
var Photo = data.response.photo;
console.log(Server);
console.log(Photo);
But now in console i see:
Uncaught TypeError: Cannot read property 'server' of undefined
Why i get errors and how get parametrs?
P.S.: All code php and jquery find here
Just set proper data type json, the default one is string.
And your data is directly under data variable!
$.post('test.php', {
id: id
},function (data) {
console.log(data);
var Server = data.server;
var Photo = data.photo;
console.log(Server);
console.log(Photo);
}, 'json');
Another solution is setting proper header in you PHP response:
Content-Type text/javascript; charset=UTF-8
then jQuery Intelligent Guess, will set proper data type itself.
You can use parseJSON method, exposed by jQuery. This enables you to map the properties to a type, of sorts, such as:
var results = jQuery.parseJSON(jsonData);
for (int i = 0; i < results.length; i++) {
alert(results[i].name + ":" + results[i].date);
}
You may need to tweak the inputs and exact use of the outputs in accordance with your data and requirements.
getJSON() will parse the JSON for you after fetching, so from then on, you are working with a simple Javascript array ([] marks an array in JSON).
You can get all the values in an array using a for loop:
$.getJSON("url_with_json_here", function(data){
for (var i=0, len=data.length; i < len; i++) {
console.log(data[i]);
}
});
Another example:
Parse a JSON string.
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" )
;

Categories

Resources