Get object from JSON with jQuery - javascript

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

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

getting json data from tree and feeding through to associative array

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.

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

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

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