How do I use an array within JSON as my data? - javascript

I have a JSON object and within that is a 2D array that has the data I need to visualise in it.
How can I pull only the array stored in 'datapoints' from the following JSON?
var myData = [
{"target": "tar.get",
"datapoints": [
[71.0, 1443793200],
[119.0, 1443793500],
[75.0, 1443793800],
[106.0, 1443794100],
[93.0, 1443794400],
[105.0, 1443794700],
[87.0, 1443795000],
[72.0, 1443795300],
[39.0, 1443795600],
[78.0, 1443795900],
[48.0, 1443796200],
[74.0, 1443796500],
[61.0, 1443796800],
[86.0, 1443797100],
[75.0, 1443797400],
[79.0, 1443797700],
[69.0, 1443798000],
[69.0, 1443798300],
[78.0, 1443798600],
[71.0, 1443798900],
[45.0, 1443799200],
[68.0, 1443799500],
[57.0, 1443799800],
[null, 1443800100]]
}];

Read some beginners guides to JSON like wiki to know the basics.
You can access it like this:
myData[0].datapoints;
You probably want to look through the mydata array like this:
var i;
for (i = 0; i < myData.length; i++) {
var datapoints = myData[index].datapoints;
// do stuff with datapoints
}

You can access JSON members as any JS object:
var datapoints = myData[0].datapoints;

Related

Initialize array of custom objects in javascript

I have data coming in from the db I need to store in a js array of objects. How do I initialize this js array of objects , so that I can keep adding the data when I get it from the db .
The object structure will be of this format
var OsNames = [{deviceName:"TV",
releases: [
{release: "rel1", hws : [{hw:"h1"},{hw:"h2"},{hw:"h3"}]},
{release: "rel2", hws: [{hw:"h1"},{hw:"h2"},{hw:"h3"}]}
]},
{deviceName:"Phone",
releases: [
{release: "rel1", hws: [{hw:"h1"},{hw:"h2"},{hw:"h3"}]},
{release: "rel2", hws: [{hw:"h1"},{hw:"h2"},{hw:"h3"}]}]
}];
var OsNames = [];
You can add data to Array by pushing elements in it when you get it from the db
e.g.
OsNames.push({release: "rel1", hws : [{hw:"h1"},{hw:"h2"},{hw:"h3"});
I think that is what you are looking for.
var osNames = [];
// Get Data from Database
var myData = ajax.get(...);
for (var i=0; i < myData.length; i++) {
osNames.push(myData[i]);
}

How to read the values inside the json array

I have a json like
var obj={
"address":{
"addlin1":"",
"addlin2":""
},
"name":"sam",
"score":[{"maths":"ten",
"science":"two",
"pass":false
}]
}
Now when Iam trying to modify the json iam try an array variable and passing above json to that like
var data=JSON.parse(obj);
var json={};
json['name']=data['name'];
json['address']={};
json['address']['addressline1']=data['address']['addlin1'];
json['address']['addressline2']=data['address']['addlin2'];
json['marks']={};
json['maths']=data['score']['maths'];
For name and address I was able to form the json as i was expecting.But for marks I was unable.May be in obj json score values are in [ ]
So,when i console the json it is in this way
"name":"sam",
"address":{
"addresslin1":"",
"addresslin2":""
},
"score":{}
}
So how can I also read the values inside [] array.
Can someone help me
Thanks
json['maths']=data['score'][0]['maths'];
if you're not sure that data['score'] has any elements you can check prior to reading maths key:
if (data['score'].length) {
json['maths']=data['score'][0]['maths'];
}
data['score'] is an array, so you can't read it like that
json['maths']=data['score']['maths'];
you have to read it like that:
json['maths'] = data['score'][0].maths;
Also, obj is not a JSON, but a JavaScript object. You can use it directly.
json['maths'] = obj['score'][0].maths;
A JSON is a string, like that:
JSON.stringify(obj)
var json = "{"address":{"addlin1":"","addlin2":""},"name":"sam","score":[{"maths":"ten","science":"two","pass":false}]}";
create another json2 to contain score data then assign to json.
for example :
var json={};
json2 = {}
json2[0] = 1;
json2[1] = 2;
json[0] = json2;

How can I omit the property names of my json and just display the values?

I wrote a small api to pull nutrition info from public diaries on MyFitnessPal. I'm pulling this information into a Google Sheet using the ImportJSON.gs found here: https://gist.github.com/paulgambill/cacd19da95a1421d3164
What I get is a two row result:
Calories Protein Fat Carbs
2458 196 82 234
My returned json looks like this:
{"Calories":"1738","Protein":"140","Fat":"78","Carbs":"119"}
I want just the numbers and not the property names. I don't want to alter the json to just return a string array, but since this is for personal usage, I will if necessary! Any ideas?
var o = {"Calories":"1738","Protein":"140","Fat":"78","Carbs":"119"}
var values = values(o); //gives you an array of values
Obviously you know how to retrieve the JSON. Just loop through the object:
function convert() {
var myJson = {"Calories":"1738","Protein":"140","Fat":"78","Carbs":"119"};
var thisKey;
var thisValue;
var newArray = [];
for (var key in myJson) {
thisKey = key;
thisValue = myJson[thisKey];
newArray.push(thisValue);
};
return newArray;
};
This creates an array of just the values.
returns: [1738, 140, 78, 119]
Simply push each value into a new array:
var values = [];
for (var i in myJson){
values.push(myJson[i])
}

Create Array using json data

My JSON data are
[
{"month":"May-2013","total_sales":"1369250"},
{"month":"June-2013","total_sales":"4328119"},
{"month":"July-2013","total_sales":"4636663"},
{"month":"August-2013","total_sales":"4754047"},
{"month":"September-2013","total_sales":"5014683"}
]
How can i craete an array in javascript from following data?
try this one
var json_data = [{"month":"May-2013","total_sales":"1369250"},{"month":"June-2013","total_sales":"4328119"},{"month":"July-2013","total_sales":"4636663"},{"month":"August-2013","total_sales":"4754047"},{"month":"September-2013","total_sales":"5014683"}];
var result = [];
for(var i in json_data)
result.push([i, json_data [i]]);
var data = '[{"month":"May-2013","total_sales":"1369250"},
{"month":"June-2013","total_sales":"4328119"},
{"month":"July-2013","total_sales":"4636663"},
{"month":"August-2013","total_sales":"4754047"},
{"month":"September-2013","total_sales":"5014683"}]'
var json = JSON.parse(data);
console.log(json);
You basically have the array object in JSON
Check http://www.mkyong.com/javascript/how-to-access-json-object-in-javascript/ also.
And to convert it back to json..
var myJsonString = JSON.stringify(yourArray);

Looping to Parse JSON Data

Description and Goal:
Essentially data is constantly generated every 2 minutes into JSON data. What I need to do is retrieve the information from the supplied JSON data. The data will changed constantly. Once the information is parsed it needs to be captured into variables that can be used in other functions.
What I am stuck in is trying to figure out how to create a function with a loop that reassigns all of the data to stored variables that can later be used in functions.
Example information:
var json = {"data":
{"shop":[
{
"carID":"7",
"Garage":"7",
"Mechanic":"Michael Jamison",
"notificationsType":"repair",
"notificationsDesc":"Blown Head gasket and two rail mounts",
"notificationsDate":07/22/2011,
"notificationsTime":"00:02:18"
},
{
"CarID":"8",
"Garage":"7",
"Mechanic":"Tom Bennett",
"notificationsType":"event",
"notifications":"blown engine, 2 tires, and safety inspection",
"notificationsDate":"16 April 2008",
"notificationsTime":"08:26:24"
}
]
}};
function GetInformationToReassign(){
var i;
for(i=0; i<json.data.shop.length; i++)
{
//Then the data is looped, stored into multi-dimensional arrays that can be indexed.
}
}
So the ending result needs to be like this:
shop[0]={7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18 }
shop[1]={}
You can loop through your JSON string using the following code,
var JSONstring=[{"key1":"value1","key2":"value2"},{"key3":"value3"}];
for(var i=0;i<JSONstring.length;i++){
var obj = JSONstring[i];
for(var key in obj){
var attrName = key;
var attrValue = obj[key];
//based on the result create as you need
}
}
Hope this helps...
It sounds to me like you want to extract the data in the "shop" property of the JSON object so that you can easily reference all of the shop's items. Here is an example:
var json =
{
"data":
{"shop":
[
{"itemName":"car", "price":30000},
{"itemName":"wheel", "price":500}
]
}
},
inventory = [];
// Map the shop's inventory to our inventory array.
for (var i = 0, j = json.data.shop.length; i < j; i += 1) {
inventory[i] = json.data.shop[i];
}
// Example of using our inventory array
console.log( inventory[0].itemName + " has a price of $" + inventory[0].price);
Well, your output example is not possible. You have what is a list of things, but you're using object syntax.
What would instead make sense if you really want those items in a list format instead of key-value pairs would be this:
shop[0]=[7,7,"Michael Jamison",repair,"Blown Head gasket and two rail mounts", 07/22/2011,00:02:18]
For looping through properties in an object you can use something like this:
var properties = Array();
for (var propertyName in theObject) {
// Check if it’s NOT a function
if (!(theObject[propertyName] instanceof Function)) {
properties.push(propertyName);
}
}
Honestly though, I'm not really sure why you'd want to put it in a different format. The json data already is about as good as it gets, you can do shop[0]["carID"] to get the data in that field.

Categories