I have this currencies.json file:
{
"USD": {
"ValueUSD": 325.33,
"ValueEUR": 344.55,
"PreviousValueUSD": 324.55,
"PreviousValueEUR": 354.55,
},
"EUR": {
"ValueUSD": 325.33,
"ValueEUR": 344.55,
"PreviousValueUSD": 324.55,
"PreviousValueEUR": 354.55,
}
}
I need to parse it into "#content" using jQuery. Can someone help me with a code to do this? I think jSONP is needed because the feed is from another server.
Example for output needed:
<div class="currency">USD, 325.33, 344.55, 324.55, 354.55</div>
<div class="currency">EUR, 325.33, 344.55, 324.55, 354.55</div>
// you will get from server
var obj = $.parseJSON(data); // data contains the string
for (var key in obj) {
$('<div class="currency" />')
.html(key + ', ' + $.map(obj[key], function(val) { return val; })
.join(', ')).appendTo('body');
}
HERE is the code.
$.parseJSON is used to parse the string into the object.
Then for each currency inside object use .map() to map the values.
Join the values into a string separated by ,, append into the div and a currency name.
Resulting div append to the body.
Update (see comments):
If you want to retrieve this data cross-domain use:
$.getJSON('www.domain.com/currencies.json?callback=?', function(data) {
for (var key in data) {
$('<div class="currency" />')
.html(key + ', ' + $.map(data[key], function(val) { return val; })
.join(', ')).appendTo('body');
}
});
Something like this should help (the data parsed from your JSON above is held in the data variable):
var $body = $("body"),
key,
$div,
txt,
innerKey;
for (key in data) {
if (data.hasOwnProperty(key)) {
$div= $("<div></div").addClass("currency");
txt = [key, ", "];
for (innerKey in data[key]) {
if (data[key].hasOwnProperty(innerKey)) {
txt.push(data[key][innerKey]);
txt.push(", ");
}
}
// Remove the trailing comma
txt.pop();
// Set the HTML content of the div and then add to the body
$div.html(txt.join("")).appendTo($body);
}
}
Here's a working example jsFiddle.
well you can access things like:
data.USD.ValueUSD will get you 325.33 so you can do something liek this. pass your data object that you get from your ajax call in ur success func to call this function:
function populateContent(data){
var $currencyDiv = $('<div class="currency"></div>'),
$currencyDiv2 = $currencyDiv.clone();
$currencyDiv.html("USD, "+data.USD.ValueUSD + ", " + data.USD.ValueEUR + ", " + data.USD.PreviousValueUSD + ", " + data.USD.PreviousValueEUR);
//do the same for currencydiv2
//append your new content divs wherever you want
$('body').append($currencyDiv);
}
A more puristic approach that could also help you understand how to iterate through objects (and is browser native and therefore not relying on jQuery)
for(var data in #YOUR_JSON_DATA# ){ // iterate through the JSON nodes
var tmp = data; // store the current node in temporary variable
for(var val in json[data]){ // iterate through the current nodes' children
tmp += ", " + json[data][val]; // this is how you access multidimensional objects. format your output as you like
}
alert(tmp); // see the output. here you could use jquery to write this into your page.
}
Related
so i want to fetch data from this api:
http://csgobackpack.net/api/GetItemsList/v2/
Its large database so i want to get only a few information for every item, like 7days price. And than save it in my file. But when i use empty obect the very first object in variable is
"[object][object]"
Request.get("http://csgobackpack.net/api/GetItemsList/v2/", {
json: true
}, (error, response, body) => {
csgo = new Object();
if(body['success']) {
for(let key in body.items_list)
csgo+=("\"" + body.items_list[key].name + "\" :{"
"\"icon\"" + ":" + "\"" + body.items_list[key].icon_url + "\","+
"\"exterior\"" + ":" + "\"" + body.items_list[key].exterior + "\"}"
}
JSON is still the source of much confusion unfortunately. JSON is text. Text that happens to be using a syntax that is very similar to how Objects are defined in JavaScript.
The code you have uses json: true, and Request.get consequently parses the reply into an Object for you. This becomes clear when you use if (body['success']), since if the API response were a string still, there wouldn't be a success property.
Which means JSON is completely out of the picture now, we're only dealing with JavaScript objects. We can access their properties using dot or brackets notation, and construct new ones.
Here's code that will grab the first 5 items and log the result:
const Request = require("request");
Request.get("http://csgobackpack.net/api/GetItemsList/v2/", { json: true }, (error, response, body) => {
// body contains the JSON reply already parsed into a JS Object
csgo = new Object();
if (body['success']) {
var limit = 5;
for (let key in body.items_list) {
// shorter way to grab multiple properties
const { icon_url, exterior } = body.items_list[key];
// add child to csgo
csgo[key] = { icon: icon_url, exterior }; // OR: exterior: exterior
if (--limit === 0) break;
}
console.log(csgo);
}
});
The key part is
csgo[key] = { icon: icon_url, exterior };
A new property is added to the object and set to the specified object literal.
SITUATION:
I have dynamic json object data and need to use it to find element.
Example:
[
{ "tag": "article",
"id": "post-316",
"order": "0" },
{ "tag": "div",
"class": "entry-content",
"order": "0" }
]
Its length, keys and values can change anytime based on user request.
I need to use that data to dynamically find the specified element in a web page. The first set of strings will be the data for parent element, which will be used to initialize the search, and the last one will be the target children.
PURPOSE:
So, from json example above, I want to find an element with:
class name entry-content, tag name div, index 0 inside of parent with id post-316
by converting that json data in such kind of format or may be simpler and or better:
// because the parent already have attribute id, so no need to check other info of this element
var elem = $("#post-316").find(".entry-content");
if(elem.prop("tagName") == "div" ) {
elem.css("background", "#990000");
}
PROGRESS:
I tried using jquery $.each() method but can't discover myself the way to achieve that purpose.
Here is the code where I currently stuck on:
var json = $.parseJSON(theJSONData);
$.each(json, function(i, e){
$.each(e, function(key, data){
alert(i + " " + key + " " + data);
if(json.length - i == 1) {
alert("target " + data);
}
if(json.length - i == json.length) {
alert("parent " + data);
}
}
);
});
QUESTIONS:
Is it possible to achieve the PURPOSE from that kind of JSON data using iteration?
If it is possible, how to do it?
If not, what the way I can use?
You can use a format so the script knows what to get:
var data = {
'id': '#',
'class': '.'
};
var json = JSON.parse(theJSONData);
$.each(json, function (a) {
$.each(data, function (b) {
if (a[b]) {
$(data[b] + a[b])[+a['order']]; // Element
}
});
});
If you are sure about the data you are getting (As in it is class, or data, and it will have a tag name):
var json = JSON.parse(theJSONData),
last = document;
$.each(json, function (a) {
var selector = (a['id']) ? '#'+a['id'] : '.'+a['class'];
last = $(last).find(a['tag']+selector)[+a['order']]; // Element
});
I know there are 1 million and 1 questions on this, but I cannot seem to find an answer.
I am receiving data via PHP as such
echo json_encode($result);
From a typical MYSQL query.
I get the result back like this in the console.
[{"id" : "1", "name" : "bob"}]
I am trying to use $.each to iterate through this so I can process my results but I only get errors, undefineds or 0[object Object].. things like that.
My goal is to append each value to a input box (retrieving data from a table to put into an edit box).
$.post('getstuff.php', { id : id } function(data){
$.each(data), function(k,v){
$('input[name= k ]').val(v);
});
});
As you can see i was hoping it was as simple as a key=>value pair but apparantly not. I have tried parsing, stringifiying.. really I am lost at this point. I also cannot tell $.post that I am using JSON because I am using a more arbitrary function, but am just posting that as my example.
Edit
var retrievedData = JSON.parse(data);
$.each(retrievedData, function(k,v){
for (var property in retrievedData) {
if (retrievedData.hasOwnProperty(property)) {
console.log(k);
console.log(v);
console.log(property);
//$('input[name= k ]').val(v);
}
}
});
In your second code sample, retrievedData is an array, which you iterate using jQuery $each...
$.each(retrievedData, function(k, v) {
OK so far. But then you try to iterate retrievedData again like an object, which it isn't. This is why you are getting undefined messages in the console
for (var property in retrievedData) {
if (retrievedData.hasOwnProperty(property)) {
console.log(k);
console.log(v);
console.log(property);
//$('input[name= k ]').val(v);
}
}
On the inner loop you should be iterating v not retrievedData. On each pass of $each v will be an object.Try this:
$.each(retrievedData, function(k,v){
for (var key in v) {
if (v.hasOwnProperty(key)) {
console.log("key: " + key);
console.log("value: " + v[key]);
}
}
});
You should do some type checking that v is an object first and catch any errors.
Use either :
$.ajax({
'dataType' : 'json'
});
Or
$.getJSON
Or if you want to use $.post, just do in your success function :
var good_data = JSON.parse(data);
$.each(good_data, function(k,v) {
$('input[name= k ]').val(v);
});
Answering your question based on your comments on other answer.
My assumption is you are getting data as JSON,if not you need to parse it,for that you can use JSON.parse(string).
Here I'm using Underscore.js
var data=[{"id" : "1", "name" : "bob"}]
$(data).each(function(ind,obj){
var keys=_.keys(obj);
$(keys).each(function(i,ke){
console.log(ke)
console.log(obj[ke]);
})
});
Here is JSFiddle of working code
First you need to define you're expecting JSON in your POST request - http://api.jquery.com/jQuery.post/
Then you need to iterate through the response.
$.post('getstuff.php', { id : id } function(data){
//Assuming you get your response as [{"id" : "1", "name" : "bob"}], this is an array
//you need to iterate through it and get the object and then access the attributes in there
$.each(data), function(item){
$('input[name=' + item.name + ']').val(item.id);
});
}, 'json');
EDIT
If you want to iterate over the properties of the objects returned, you need to put another loop inside the $.each
for (var property in item) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
More about it here - Iterate through object properties
EDIT 2
To address the solution you've posted. You've used the wrong variable names. Here's a working fiddle - http://jsfiddle.net/EYsA5/
var $log = $('#log');
var data = '[{"id" : "1", "name" : "bob"}]'; //because we're parsing it in the next step
var retrievedData = JSON.parse(data);
for (var parentProp in retrievedData) { //this gets us each object in the array passed to us
if (retrievedData.hasOwnProperty(parentProp)) {
var item = retrievedData[parentProp];
for (var property in item) { //this gives us each property in each object
if (item.hasOwnProperty(property)) {
console.log(item[property]);
$log.prepend("<br>");
$log.prepend("Property name is - " + property);
$log.prepend("<br>");
$log.prepend("Value of property is - " + item[property]);
//do stuff
}
}
}
};
I am getting the data from an API using JavaScript.
The statement console.log(json[0]) gives the result:
{"id":"1","username":"ghost","points":"5","kills":"18","xp":"10","diamonds":"0","level":"1","missionscomplete":"1"}
Now I am trying to print the individual elements of this dictionary. How do I do this ? My code is below:
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
var json = $.parseJSON(data);
console.log(json[0]);
$.each(json[i], function(key, data) {
console.log(key + ' -> ' + data);
});
});
}
EDIT:
The value of data as returned by the API is
["{\"id\":\"1\",\"username\":\"ghost\",\"points\":\"5\",\"kills\":\"18\",\"xp\":\"10\",\"diamonds\":\"0\",\"level\":\"1\",\"missionscomplete\":\"1\"}","{\"id\":\"2\",\"username\":\"seconduser\",\"points\":\"0\",\"kills\":\"3\",\"xp\":\"0\",\"diamonds\":\"0\",\"level\":\"0\",\"missionscomplete\":\"0\"}","{\"id\":\"3\",\"username\":\"goat\",\"points\":\"12\",\"kills\":\"13\",\"xp\":\"14\",\"diamonds\":\"10\",\"level\":\"10\",\"missionscomplete\":\"4\"}"]
The value in json after the operation var json = $.parseJSON(data); is
["{"id":"1","username":"ghost","points":"5","kills":…diamonds":"0","level":"1","missionscomplete":"1"}", "{"id":"2","username":"seconduser","points":"0","ki…diamonds":"0","level":"0","missionscomplete":"0"}", "{"id":"3","username":"goat","points":"12","kills":…amonds":"10","level":"10","missionscomplete":"4"}"]
You can just use stringify method of JSON-
console.log(JSON.stringify(json[0]));
Update
Your JSON data is a mess. It's not in the format you want. It should be an array of objects, but instead it is an array of strings, where each of those strings is the JSON representation of one of your user objects.
You could decode this in your JavaScript code, but you shouldn't have to. The JSON API should be fixed to generate a reasonable JSON object.
I don't know what language your server code is in, but it must be doing something like this pseudocode:
array = []
for each userObject in leaderBoard:
userJson = toJSON( userObject )
array.push( userJson )
jsonOutput = toJSON( array )
Instead, the code should look more like this:
array = []
for each userObject in leaderBoard:
array.push( userObject )
jsonOutput = toJSON( array )
In other words, the way to generate the JSON you want in most languages is to create an object or array with the structure you need, and then call the language's toJSON function (or whatever function you use) on that object or array. Let it generate all of the JSON in one fell swoop. Don't generate JSON for each individual element of your array and then generate JSON again for the entire array as a whole. That gives you an array of strings where you want an array of objects.
Original answer
What you're asking for is not what you really want to do.
Your JSON response returns an array of user objects, correct? That's why json[0] is a single object.
You probably want to loop over that array, but you don't loop over the individual objects in the array. You simply reference their properties by name.
Also, instead of using $.get() and $.parseJSON(), you can use $.getJSON() which parses it for you.
And one other tip: don't put the hostname and port in your URL. Use a relative URL instead, and then you can use the same URL in both development and production.
So for test purposes, let's say you want to log the id, username, and points for each user in your leaderboard JSON array. You could do it like this:
function loadLeaderboard() {
var url = '/l4/public/api/v1/getLeaderboard';
$.getJSON( url, function( leaders ) {
// leaders is an array of user objects, so loop over it
$.each( leaders, function( i, user ) {
// get the properties directly for the current user
console.log( user.id, user.username, user.points );
});
});
}
json[0] is an object, so you want to loop over the keys:
var o = json[0];
for (var key in o) {
if (o.hasOwnProperty(key)) {
console.log(key, o[key]);
}
}
Working fiddle: http://jsfiddle.net/UTyDa/
jQuery.each() is probably the easiest way, check this out: http://api.jquery.com/jQuery.each/
eg
$.each(json[0], function(key, data) {
console.log(key + ' -> ' + data);
});
EDIT:
What's the result of the following?
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
var json = $.parseJSON(data);
console.log(json[0]);
for(var i = 0; i < json.length; i++) {
$.each(json[i], function(key, data) {
console.log(key + ' -> ' + data);
});
}
});
}
EDIT 2: 'data' returned as array.
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard", function(data){
for(var i = 0; i < data.length; i++) {
var json = $.parseJSON(data[i]);
console.log('Data for index: ' + i);
$.each(json, function(key, val) {
console.log(key + ' -> ' + val);
});
}
});
}
I've got some JSON data that is giving me a list of languages with info like lat/lng, etc. It also contains a group value that I'm using for icons--and I want to build a legend with it. The JSON looks something like this:
{"markers":[
{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}
]}
And I want to "filter" it to end up like this:
{"markers":[
{"group":"a", "value":"yes"},
{"group":"b", "value":"no"},
{"group":"c", "value":"NA"}
]}
Right now I've got this, using jQuery to create my legend..but of course it's pulling in all values:
$.getJSON("http://127.0.0.1:8000/dbMap/map.json", function(json){
$.each(json.markers, function(i, language){
$('<p>').html('<img src="http://mysite/group' + language.group + '.png\" />' + language.value).appendTo('#legend-contents');
});
});
How can I only grab the unique name/value pairs in the entire JSON object, for a given pair?
I'd transform the array of markers to a key value pair and then loop that objects properties.
var markers = [{"language":"Hungarian","group":"a", "value":"yes"},
{"language":"English", "group":"a", "value":"yes"},
{"language":"Ewe", "group":"b", "value":"no"},
{"language":"French", "group":"c", "value":"NA"}];
var uniqueGroups = {};
$.each(markers, function() {
uniqueGroups[this.group] = this.value;
});
then
$.each(uniqueGroups, function(g) {
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + this).appendTo('#legend-contents');
});
or
for(var g in uniqueGroups)
{
$('<p>').html('<img src="http://mysite/group' + g + '.png\" />' + uniqueGroups[g]).appendTo('#legend-contents');
}
This code sample overwrites the unique value with the last value in the loop. If you want to use the first value instead you will have to perform some conditional check to see if the key exists.
How about something more generic?
function getDistinct(o, attr)
{
var answer = {};
$.each(o, function(index, record) {
answer[index[attr]] = answer[index[attr]] || [];
answer[index[attr]].push(record);
});
return answer; //return an object that has an entry for each unique value of attr in o as key, values will be an array of all the records that had this particular attr.
}
Not only such a function would return all the distinct values you specify but it will also group them if you need to access them.
In your sample you would use:
$.each(getDistinct(markers, "group"), function(groupName, recordArray)
{ var firstRecord = recordArray[0];
$('<p>').html('<img src="http://mysite/group' + groupName+ '.png\" />' + firstRecord.value).appendTo('#legend-contents');
}
See this-
Best way to query back unique attribute values in a javascript array of objects?
You just need a variation that checks for 2 values rather than 1.
var markers = _.uniq( _.collect( markers , function( x ){
return JSON.stringify( x );
}));
reference