Parsing JSON and loading into array - javascript

JSON-https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo
I am trying to take the JSON from the above link and place it in the following format(date,open,high,low,close)...
[
[1277424000000,38.58,38.61,37.97,38.10],
[1277683200000,38.13,38.54,37.79,38.33],
[1277769600000,37.73,37.77,36.33,36.60],
[1277856000000,36.67,36.85,35.72,35.93],
]
The date does not need to be Epoch time.
My code....
$.getJSON('https://www.alphavantage.co/query?
function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo', function(data) {
//Get the time series data
var timeseries = data['Time Series (Daily)']
var ohlcarray = [];
//Loop through each time series and convert it to JSON format
$.each(timeseries, function(key, value) {
var ohlcdata=[];
ohlcdata[0]=value[0];//date
ohlcdata[1]=value[1];//open
ohlcdata[2]=value[2];//high
ohlcdata[3]=value[3];//low
ohlcdata[4]=value[4];//low
ohlcarray.push(ohlcdata);
});
console.log(ohlcarray[0]);//test if worked properly
});
The output....
[undefined, undefined, undefined, undefined, undefined]
value[x] returns undefined. Any ideas on why this happens?
Thanks!

The reason is that in the each loop, the value is not a list but an object. To access it, you'd have to grab it using keys.
ohlcdata[0] = key; //date
ohlcdata[1] = value['1. open']; //open
ohlcdata[2] = value['2. high']; //high
ohlcdata[3] = value['3. low']; //low
ohlcdata[4] = value['4. close']; //low
https://jsfiddle.net/koralarts/7c2fkf93/2/

At this point it is already JSON. As Patrick mentioned, getJSON automatically parses json. You will need to access it with the array bracket notation since there are spaces in the property name.
var timeSeries = data['Time Series (Daily)'];
See ex: https://jsfiddle.net/dz0phhn2/6/

Related

JSON to JS array

JSON:
[{"CDATE":"0000-00-00","DISTANCE":"0"},
{"CDATE":"0000-00-00","DISTANCE":"1"},
{"CDATE":"0000-00-00","DISTANCE":"2"},
{"CDATE":"0000-00-00","DISTANCE":"3"}]
Is it possible to put all the distance value in their own array in JS? The formatting will be consistent as it comes from an API and is always formatted correctly.
What I've tried:
var arry = [ /* JSON noted above */ ];
alert(arry[1])
and
var arry = JSON.parse([ /* JSON noted above */ ]);
alert(arry[1])
Expected:
1
Actual:
{"CDATE":"0000-00-00","DISTANCE":"1"}
and the other gives an error.
I would like to extract just the DISTANCE value as an array of DISTANCE
I've tried JSON.parse() but I don't think this is what I am after as it hasn't worked for me.
Use .map
var data = [{"CDATE":"0000-00-00","DISTANCE":"0"},
{"CDATE":"0000-00-00","DISTANCE":"1"},
{"CDATE":"0000-00-00","DISTANCE":"2"},
{"CDATE":"0000-00-00","DISTANCE":"3"}];
var distance = data.map(el => el.DISTANCE);
console.log(distance[2]);
console.log(distance);
It is already a valid json so you do not need to use JSON.parse()

JavaScript return object property value

I have this object:
{"Header":["Date","Test1","Test2","Test3","N/A","Test4","Test5"],
"Values":[["Total Unique","79 280","1 598","5 972","20","2 633","9 696"],
["2017-06-19","28 026","1 036","3 667","20","1 097","4 672"]]}
My desired result is this:
Date
2017-06-19
What I was able to achieve:
Date ["2017-06-19","28 026","1 036","3 667","20","1 097","4 672"]
Using this code:
vm.header = data.Header[0];
vm.data1 = data.Values[1];
Because data.Values is a two-dimensional array you can get the desired result by changing the code to:
vm.header = data.Header[0];
vm.data1 = data.Values[1][0];
Header[0] = 'Date';
Header[1]= 'Test1';
Header[2]= 'Test2';
Header[3]= 'Test3';
Header[4]= 'N/A';
Header[5]= 'Test4';
Header[6]= 'Test5';
Values is 2D array
Values[0] = ["Total Unique","79 280","1 598","5 972","20","2 633","9 696"]
Values[1]=["2017-06-19","28 026","1 036","3 667","20","1 097","4 672"]
What you have tried so far is data.Header[0] would give you 'Date'. data.Values[1] would give you whole array. So you need to get "2017-06-19" you have to get first element of that array ie data.Values[1][0]

JQuery - How to loop through JSON using each

I have cached the JSON returned from an Ajax call and need to loop through this to display it. I get the error, 'Cannot read property 'title' of undefined'. Can anyone help?
$.each(cache['cat-'+cat], function(i, jd) {
var title= jd.title; //issue is here
)}
When I console.log(cache['cat-'+cat]) I get the below:
Object {
date: "2016-07-28T15:08:03.596Z",
data: '[{"id":471,"title":"Lines and Calls","solution_areas":"lines-calls"}]'
}
When I console.log(jd) within the loop I get the below:
2016-07-28T15:13:14.553Z
if I use console.log(jd.data); I get
undefined
I have tried the below but they don't work either:
var title= jd.data.title;
var title= jd.data[0].title;
Can anyone tell me what I am doing wrong?
The way you are currently using it, each is going to iterate over every property of the cache['cat-'+cat] object, of which there are two, date and data.
So your anonymous function function(i, jd)will be called twice. The first time, jdwill be the value of the date property (a string), the second time it will be the value of the data property (also a string, that happens to be formatted as JSON).
The contents of data need to be parsed before they can be accessed as an object/array, and given that data is formatted as an array, I am guessing that you actually want to iterate over that. Given the example provided, I would change it to:
$.each(JSON.parse(cache['cat-'+cat].data), function(i, jd) {
var title= jd.title;
});
You aren't accessing it properly. And since cache['cat-'+cat] is already the needed object, what's the purpose of $.each? Should be
var title= JSON.parse(cache['cat-'+cat].data)[0].title;
(because the title is in the data, and the data is JSON).
Demo:
var obj = {
date: "2016-07-28T15:08:03.596Z",
data: '[{"id":471,"title":"Lines and Calls","solution_areas":"lines-calls"}]'
};
var title= JSON.parse(obj.data)[0].title;
console.log(title);
Just need to understand what is JSON and what is STRING
cache['cat-'+cat].data return a string that need to convert to JSON before pass to each loop:
var dataCacheReturned = cache['cat-'+cat];
var objCache = dataCacheReturned.data; //Its return a string
objCache = JSON.parse(objCache); //Parse string to json
$.each(objCache, function(i, jd) {
var title = jd.title;
console.log(title);
});

fetch data from nested JSON object in a single line

This is my JSON data ....
{"comp1":["$.Create_Keypair1_Keypair_name"]}
I want to get the value "Create_Keypair1_Keypair_name".but all the keys and values are dynamic.but the object always have single data.
I have Object.keys(temp).It shows only ["comp1"] i need
$.Create_Keypair1_Keypair_name only....
Try this:
var data = {"comp1":["$.Create_Keypair1_Keypair_name"]}
for (var key in data) {
console.log(data[key])
}
This will log $.Create_Keypair1_Keypair_name.
From what I am understanding each object will have a single value. If the is the case then you do not need the array in the object. You can do this.
var tempy = {"comp":"ksmdfnsfdnsdfn"}
Then do this to ge the value.
tempy.comp
Or if you need the keys.
Object.keys(tempy)
you might be looking for this
var temp = {"comp1":["$.Create_Keypair1_Keypair_name"]}
Object.keys(temp).forEach(function(key){
console.log(temp[key]);
});

Javascript [Object object] error in for loop while appending string

I am a novice trying to deserialize my result from an onSuccess function as :
"onResultHttpService": function (result, properties) {
var json_str = Sys.Serialization.JavaScriptSerializer.deserialize(result);
var data = [];
var categoryField = properties.PodAttributes.categoryField;
var valueField = properties.PodAttributes.valueField;
for (var i in json_str) {
var serie = new Array(json_str[i] + '.' + categoryField, json_str[i] + '.' + valueField);
data.push(serie);
}
The JSON in result looks like this:
[
{
"Text": "INDIRECT GOODS AND SERVICES",
"Spend": 577946097.51
},
{
"Text": "LOGISTICS",
"Spend": 242563225.05
}
]
As you can see i am appending the string in for loop..The reason i am doing is because the property names keep on changing therefore i cannot just write it as
var serie = new Array(json_str[i].propName, json_str[i].propValue);
I need to pass the data (array type) to bind a highchart columnchart. But the when i check the var serie it shows as
serie[0] = [object Object].Text
serie[1] = [object Object].Spend
Why do i not get the actual content getting populated inside the array?
You're getting that because json_str[i] is an object, and that's what happens when you coerce an object into a string (unless the object implements toString in a useful way, which this one clearly doesn't). You haven't shown the JSON you're deserializing...
Now that you've posted the JSON, we can see that it's an array containing two objects, each of which has a Text and Spend property. So in your loop, json_str[i].Text will refer to the Text property. If you want to retrieve that property using the name in categoryField, you can do that via json_str[i][categoryField].
I don't know what you want to end up with in serie, but if you want it to be a two-slot array where the first contains the value of the category field and the second contains the value of the spend field, then
var serie = [json_str[i][categoryField], json_str[i][valueField]];
(There's almost never a reason to use new Array, just use array literals — [...] — instead.)

Categories

Resources