Reading unlabelled JSON arrays - javascript

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

Related

How do I get a buried variable from a JSON file?

This is probably a very novice question, but I am a very novice programmer, so here goes...
I am using GAS and Google Books to get the url for a book cover using this code:
function myFunction() {
var url = "https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&country=US"
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(response);
}
From my limited knowledge, I tried using this to get the proper URL:
Logger.log(data.items.imageLinks.smallThumbnail);
but it just returns an error. Is there something missing or a different way to get the variable I need?
The issue is that data.items is an array of 10 elements, therefore you have to index that.
If you want to access the first element:
function myFunction() {
var url = "https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&country=US"
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(data.items.length)
Logger.log(data.items[0].volumeInfo.imageLinks.smallThumbnail);
}
If you want to access all elements and store it in an array:
function myFunction() {
var url = "https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&country=US"
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var items = data.items;
var smallThumbnails = items.map(x=>x.volumeInfo.imageLinks.smallThumbnail);
Logger.log(smallThumbnails);
}
Output:
[http://books.google.com/books/content?id=gK98gXR8onwC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=LRlCAAAAYAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=Fgn65IL3q4wC&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=3vFDvgAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=gK98gXR8onwC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=F1wgqlNi8AMC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=64tuPwAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=wAUiAAAAMAAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=7hLQ_F0obXAC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=tVxnDwAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api]

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

JS: Textfile to JSON

im a complete beginner to JS and need some help.
I have a Textfile looking like this:
JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON
2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held
2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held
2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None
So JOBID, NAME and so on are the Names for the values below.
Now I want to parse it into a JSON object.
I tried to do it like this:
var jdata = new Array();
jdata = data.toString().split('\n');
jsonstring = JSON.stringify(jdata);
fs.writeFile('out/data.json', jsObj, (err) => {
if (err) throw err;
});
But the result is no JSON object right?
I somehow need to attach connect the parameters to each other so it looks like:
{
"JOBID": 2527,
"NAME": '_DP-2-Q-095-84-1-50.job',
...
}
Somebody can tell me how to convert this correctly or isn't it even possible this way?
Thank you already
You've started correctly but you cannot simply use JSON.stringify(jdata); to convert to JSON. An example in pure JS is like so:
//Load in Input
var input = `JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON
2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held
2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held
2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None`;
//Split into Lines
var data = input.split("\n");
//Get all the header values
var header = input.split("\n")[0].split(",");
//Init Output Array
var output = [];
//For every row except the first (1...n)
for(var i=1;i<data.length;i++){
//Get all the values
var values = data[i].split(",");
var obj = {};
//For every value in the header
for(var j=0;j<header.length;j++){
//obj[JOBID] = 2527
obj[header[j]] = values[j];
}
//Push to output
output.push(obj);
}
Output now will equal your array of objects. You can then save it as you did before.
// [{"JobID": 2527, "...},{..}...]
jsonstring = JSON.stringify(output);
fs.writeFile('out/data.json', jsObj, (err) => {
if (err) throw err;
});
You are correct that you need to transform your data before it becomes a proper JSON object.
This is a way to do it (with a bit more modern Javascript):
const data = `JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON
2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held
2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held
2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None
`;
let lines = data.split('\n');
const headers = lines.shift().split(',');
// convert the individual lines to JSON objects
const jsonData = lines.map(line => {
const parts = line.split(',');
// Invalid lines - these are filtered out later
if (parts.length !== headers.length) {
return false;
}
// look up the name of the part from the header and use that as the property name
return parts.reduce((acc, part, index) => ({
...acc,
[headers[index]]: part,
}), {});
}).filter(Boolean); // remove the invalid objects
console.log(jsonData);
Here is a simple approach and you can modify it as for your need
var data = 'JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON\n'
+'2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held\n'+
'2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held\n'+
'2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None';
var spdata = data.split('\n');
//assuming that the first row is always having columns names
var names = spdata[0].split(',');
var mainDataAr=[];
//reading data from the 2nd row
for(var i=1;i<spdata.length;i++)
{
//taking the data from the row at position i
var rdata = spdata[i].split(',');
var obj={};
for(var j=0;j<names.length;j++)
{
obj[names[j]]=rdata[j]
}
mainDataAr.push(obj);
}
console.log(mainDataAr);

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

javascript 'object object' from localstorage

I am getting an alert saying [object] object when I execute showlogsf function
var fdata = {fidval, fweightval, feggslaidval, fgraineatenval, fwaterval};
var fidval = document.getElementById('#fid');
var fweightval = document.getElementById('#fweight');
var feggslaidval = document.getElementById('#feggslaid');
var fgraineatenval = document.getElementById('#fgraineaten');
var fwaterval = document.getElementById('#fwater');
These are the two functions that could be triggered from button click
$('#submitf').click(function (){
localStorage.setItem ("fdatak", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload);
});
});
You're pushing an object as an alert. the HTML displays this as [object Object]. You have to address the actual properties of this object, so:
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload.fidval);
alert(fdataload.fweightval);
alert(fdataload.feggslaidval);
// etc etc...
});
EDIT: Seems like you're also saving the document element, rather than the value. I assume the fdataload.properties are actual values, you should either grab the raw HTML data or input value of this instead of the HTML element itself
I guess your fdata is an array right?.
Try this var fdata = [fidval, fweightval, feggslaidval, fgraineatenval, fwaterval];
I edited values of array as xxx.value instead of xxx
var fdata = new Array();
$('#submitf').click(function (){
var fidval = document.getElementById('fid');
var fweightval = document.getElementById('fweight');
var feggslaidval = document.getElementById('feggslaid');
var fgraineatenval = document.getElementById('fgraineaten');
var fwaterval = document.getElementById('fwater');
var fdata = [];
like this
fdata.push (fidval.value, fweightval.value, feggslaidval.value, fgraineatenval.value, fwaterval.value);
localStorage.setItem ("fdata", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem('fdata'));
document.getElementById("flogview").innerHTML = fdataload;
});
Now it saves but I have another problem, why it is replacing data every time I click showlogsf button??

Categories

Resources