Getting the lengh of an JSON array - javascript

I am having a json file. I can get the data in the json file using
$.getJSON.json("mock/Insight72.json", function (jsondata) {
response = jsondata.Data1;
response2 = jsondata.Data2;
});
But I want to find the length of the Data1 and Data2. What should I do?
Here`s the JSON data(Only the Fruit Part)..
],
"Data1": {
"kitchen selectives": [{
"displayColor": "#DC143C",
"numProducts": 1,
"averagePrice": 25.99,
}],
"aroma": [{
"displayColor": "#991F1F",
"numProducts": 1,
"averagePrice": 60.25,
}, {
"displayColor": "#DC143C",
"numProducts": 1,
"averagePrice": 46.19,
}, ............

As Data1 appears to be an Object ({...}), it'll only have a length if one was explicitly given as another key/value:
{
"aroma": [],
"length": 2
}
However, if you'd like to know the number of keys/properties it has, you can use Object.keys():
var keyCountData1 = Object.keys(jsondata.Data1).length;
You can also retrieve the length of any Array ([...]) within Data1, such as "aroma":
var aromas = jsondata.Data1.aroma.length;
Or, if you want to know the length of the Object as JSON:
var dataLength = JSON.stringify(jsondata.Data1).length;
Beyond that, however, you'll have to clarify exactly what "length" you're hoping for.

To find out how many elements are in the response object, you can do something like:
var length = 0;
for (var key in response) {
response.hasOwnProperty(key) && ++length;
}
If you want to find out the total length of all the arrays under it, you can do something like:
var length = 0;
for (var key in response) {
response.hasOwnProperty(key) && length += response[key].length;
}

You can use two different approaches
This one is not compatible with IE7 and 8. Look here as well.
var length = Object.keys(response).length;
var length2 = Object.keys(response2).length;
This one will itterate through json and return length:
function getJSONLegth(response) {
var count = 0;
for (var k in response) {
count++;
}
return count;
}
var length = getJSONLegth(response);
var length2 = getJSONLegth(response2);
Did it help you?

Related

Get array from json using javascript

Server returns me such object, but i need only array ITEMS.
How can i get it?
I tried array['items'] but the result is undefiend
{
"items": [
{
..
},
{
..
},
{
..
}
],..
,..
}
// JSON string returned from the server
var text = '{"items":[{"name":"itemX" ,"price":15},{"name":"itemY","price":25},{"name":"itemZ","price":20}]}';
// Convert the string returned from the server into a JavaScript object.
var object = JSON.parse(text);
// Accessing a specific property value of an item
console.log(object.items[0].name); //itemX
// Extract 'items' in to a separate array
var itemsArray = object.items;
console.log(itemsArray); //[itemObject, itemObject, itemObject]
If you're getting this as a string:
var json = JSON.parse(my_json_string)
Then,
var keys = Object.keys(json);
var values = [];
for(var i = 0; i < keys.length; i++){
values.push(json[keys[i]]);
}

Insert a array in a JSON object

I have two arrays called one and two. one contains string values and two int values.
I'm trying:
var messageObject = { 'One': one,
'Two': two};
var serializedJSON = JSON.stringify(messageObject);
var json = JSON.parse(serializedJSON);
alert(json.One);
I'm getting "Undefined", though the array is populated.
They are receiving data from a database, like this:
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM aluno', [], function(transaction, results) {
len = results.rows.length, i;
for (i = 0; i < results.rows.length; i++) {
one[i] = results.rows.item(i).fieldOne;
two[i] = results.rows.item(i).fieldTwo;
}
}, null);
});
See the code:
http://jsfiddle.net/U4C6r/2/
Edited Answer:
The problem seems to be with the DB-Query-Code. Either the query or the callback get never executed, see: http://jsfiddle.net/U4C6r/11/
Original Answer:
var messageObject = {
'One': one,
'Two': two
};
If you define your keys as strings, you should access them as such:
console.log(json['One']);
If you'd like to have them as properties on the object, you should do:
var messageObject = {
One: one,
Two: two
};
Then you could access the data in a chaining fashion, like you want to:
console.log(json.One);
You should also see the difference here and in your IDE
by the specific Syntax-Highlighting - see it? :)
EDIT to updated:
put breakpoint as you read the values from webSQL and check the structure of object you get within loop inspect this obj results.rows.item(i)
Also change your script to this. I am assuming you have global var one = []; and var two = []; declared.
var dynamicArrayContainer = { one : [],
two : []};
db.transaction(function(transaction) {
transaction.executeSql('SELECT * FROM table', [], function(transaction, results) {
for (var i = 0; i < results.rows.length; i++) {
dynamicArrayContainer .one.push(results.rows.item(i).fieldOne);
dynamicArrayContainer .two.push( results.rows.item(i).fieldTwo);
}
}, null);
});
Try this, put your values directly, as debug exercise
var serializedJSON = JSON.stringify(dynamicArrayContainer);
var json = JSON.parse(serializedJSON);
alert(json.one);
Try this:
var messageObject = { One: 'one',
Two: 'two'};
var serializedJSON = JSON.stringify(messageObject);
var json = JSON.parse(serializedJSON);
alert(json.One);
Good luck
:)
Update: Enquirer edited the query after this reply was posted. This reply pertains to the original query (ie the first part of the current query)

Find specific key value in array of objects

This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}

Manipulation of Javascript objects

I have an object in my javascript which looks like this:
{"data":[{"t":{
"level":"35",
"longtitude":"121.050321666667",
"latitude":"14.6215366666667",
"color":"#040098"}},
{"t":{
"level":"31",
"longtitude":"121.050316666667",
"latitude":"14.621545",
"color":"#040098"}},
{"t":{
"level":"29",
"longtitude":"121.050323333333",
"latitude":"14.62153",
"color":"#040098"}},
// .....
What I would like to do is to iterate thru the contents of my object so that I will be able to push them to their respective arrays independently.
I have an array for longitude, latitude, color and level.
So I have tried the following:
var size = 0, key;
for (key in result) {
if (result.hasOwnProperty(key)) size++;
alert(result.data[size]);
}
-->But this only alerts me "[object Object]"
success: function(result){
var size = 0, key;
for (key in result) {
for(var attr in key){
alert(attr['latitude']);
}
}
}
-->This gives me Undefined result[key]
I have checked that the size of my object is only 1 thru these codes
var size = 0, key;
for (key in result) {
if (result.hasOwnProperty(key)) size++;
}
alert(size);
I believe that only "data" is being read. And others that are inside "data" are disregarded.
I have read this, this, enter link description here, and this but they sall seem to deal with a different structure of objects. Thanks for the help in advanced.
UPDATE
Using the console.log(), I have confirmed, if im not mistaken that only the first attribute is being fetched
t
Object { level="35", longtitude="121.0508", latitude="14.6204083333333", more...}
color "#040098"
latitude "14.6204083333333"
level "35"
longtitude "121.0508"
I tried this
for (key in result) {
if (result.hasOwnProperty(key)) size++;
console.log(result.data[size]['level']);
}
--> but it says undefined
based on the structure of my object which is
data:[{"t":{'others'},'others'...]
How am I to read everything inside "data"? Each "data" has "t".
Update: Using the for...in construct for iterating over arrays isn't recommended. The alternative is a regular for loop (each method of course having their respective advantages):
for(var i=0; i<results.data.length; i++){
alert(results.data[i]['t']['latitude']);
// etc...
}
Be careful with the structure of your JSON. Also note that the javascript foreach loop iterates over keys/indices -- not values. See demo: http://jsfiddle.net/g76tN/
success: function(result){
var latitudes = [];
// and so on...
for (var idx in result.data ) {
if( result.data.hasOwnProperty(idx) ){
alert( result.data[idx]['t']['latitude'] );
// So you would do something like this:
latitudes.push ( result.data[idx]['t']['latitude'] );
// and so on...
}
}
}​
Note for collecting properties of objects in an array, jQuery $.map() -- or native js array map for that matter -- is a neat, useful alternative.
var latitudes = $.map( result.data, function(n){
return n['t']['latitude'];
});
// and so on...
Assuming result is your object, this should just be a matter of iterating over your data array:
for (var i = 0; i < result.data.length; ++i) {
console.log(result.data[i].t.latitude);
...
}
It's not hard to do, as shown below. But why would you want to take useful objects like your t's and turn them into such arrays?
var levels = [], longitudes= [], latitudes = [], colors = [];
var result = {"data":[{"t":{
"level":"35",
"longtitude":"121.050321666667",
"latitude":"14.6215366666667",
"color":"#040098"}},
{"t":{
"level":"31",
"longtitude":"121.050316666667",
"latitude":"14.621545",
"color":"#040098"}},
{"t":{
"level":"29",
"longtitude":"121.050323333333",
"latitude":"14.62153",
"color":"#040098"}}
]};
var data = result.data;
var i, len, t;
for (i = 0, len = data.length; i < len; i++) {
t = data[length].t;
levels[i] = t.level;
longitudes[i] = t.longtitude;
latitudes[i] = t.latitude;
colors[i] = t.color;
}
See http://jsfiddle.net/VGmee/, which keeps the hasOWnProperty (which is important), and your misspelling of "longitude", which is not.
var data = input.data,
result = {level: [], longtitude: [], latitude: [], color: []};
for (var i = 0, n = data.length; i < n; i += 1) {
var info = data[i].t;
for (var property in info) {
if (info.hasOwnProperty(property)) {
result[property].push(info[property]);
}
}
}
console.log(result.level);
console.log(result.latitude);
console.log(result.longtitude);
console.log(result.color);
This requires the result arrays to actually have the properties in your input array, but you can add error handling as desired.

Get Length of json Data

i have this json data and i want to get length of this json data and also of css
my json data is shown here
jso({tag:"div",css:{backgroundColor:"red"},html:"abc"})
i have pass this in function
function jso(data){
alert(data.length)
}
Your JSON is not a valid JSON object
{
"tag": "div",
"css": {
"backgroundColor":"red"
},
"html":"abc"
}
However proper JSON object don't have a length attribute, so you need to iterate over them to calculate the length.
i know what u mean u just need to loop over your object with a counter variable
var x = {tag:"div",css:{backgroundColor:"red"},html:"abc"}
function objectLength(obj){
var counter = 0;
for(var i in obj)
{
counter +=1;
}
return counter
}
use it like this
alert(objectLength(x))
To iterate over the data using jQuery counting how many iterations you did do the following:
var data = {tag:"div",css:{backgroundColor:"red"},html:"abc"};
var count = 0;
$.each(data, function(key, value) {
count++;
});
See jsFiddle here.
To iterate over the data using JavaScript only counting how many iterations you did do the following:
var data = {tag:"div",css:{backgroundColor:"red"},html:"abc"};
var count = 0;
var key;
for(key in data)
{
var value = data[key];
count++;
}
​See jsFiddle here.

Categories