how to get length of json encoded array in javascript? - javascript

I have a json encoded array like this:
{
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
my quetion is :
(1) How to find length of this array? //here it is 3
(2) How to use it's value?
//for example:for as0 the value is {\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}
javascript code where i use upper things :
function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':false }
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
})
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
alert(JSON.parse(jax.responseText).ar0);
try {
console.log(jax.responseText);
//it is not work
for(var i=0;i<JSON.parse(jax.responseText).length;i++)
{
setroute( eval('(' + jax.responseText + ')') );
}
}
catch(e){ alert(e); }
}}
}

Your JSON is not an array, but an object. If you want it to be an array, it should be something like this:
[
"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
]
Then, you can get a javascript array as follows:
var array = JSON.parse(jax.responseText);
And access values as follows:
array[0]
array.length
EDIT: In order to have a real JSON array with the PHP json_encode method, see this related question.
With this modification you will be able to use all the possibilities of JS array without workaround.

Objects in JavaScript don't have a .length property like Arrays do.
In ES5 you can do: Object.keys({}).length; // 0
The other solution would be to loop over all the properties of your object with a for .. in loop and count.

You can use the following code. It will produce your desired output 3
var test = {
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
var getLength = function(obj) {
var i = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)){
i++;
}
}
return i;
};
console.log(getLength(test));

For your first question, you should use Object.keys(item).length
To get the values of your object, you should iterate over it with a for loop:
for(var key in item)
{
var val = item[key];
}

var count = 0;
Object.keys(json).forEach(function (key) {
count++;
alert(json[key].start.lat);
});
alert(count);
Using jQuery
$(json).each(function() { count++; alert(this.start.lat); });
alert(count);

Related

fetch the array having specific value

I have the json array value which have age and number.I want to create a new set of array which has {"num":2} in it (ie)need to return [{"age":2,"num":2},{"age":3,"num":2}]
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(array_val) {
return array_val = {"num":1};
}
array_val.filter(fetchList)
console.log(array_val);
I see 2 issues in your code:
You don't parse your string to JSON
You have a wrong filter
function
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(array_val) {
return array_val.num === 2; // return only records whose num is 2
}
// here you parse string into JSON and apply the filter
var data = JSON.parse(array_val).filter(fetchList);
console.log(data);
You need to use filter()
var fetched_object = array_val.filter(function(obj) {
return obj.num == 1;
});
Note: Like #NinaScholz said you need to JSON.parse the string so it is an array.
You need parse the JSON string JSON.parse() .And matching condition was wrong .num is the inner propery of the object .so you need to match a.num == 2 .Don't forget to add ==
var array_val='[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]';
console.log(array_val);
function fetchList(a) {
return a.num == 2;
}
var res = JSON.parse(array_val).filter(fetchList)
console.log(res);
This should do it
var array_val=JSON.parse('[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]');
console.log(array_val);
function fetchList(array_val) {
return array_val.num == 2;
}
array_val = array_val.filter(fetchList)
console.log(array_val);
This would work instead:
var requiredValue = array_val.filter(function(item) { return item.num === 2;
});
try this
var array_val=JSON.parse('[{"age":1,"num":1},{"age":2,"num":2},{"age":3,"num":2}]');
var newarr =[]
for(let i of array_val){
if(i.num == 2){
newarr.push(i);
}
}
console.log(newarr);

Accessing dynamic values from JSON object in javascript

this is my json object. i need to get only all the values of packageName and assign it to an array. can any body help me with that. i can not go for using indexes since this is dynamic object.
thanks in advance.
var data = [
{
"packageName":"string",
"packageValue":"string"
},
{
"packageName":"string",
"packageValue":"string"
}
]
Use javascript map function
var packageNames = data.map(function(obj){
return obj.packageName;
})
var data=[
{
"packageName":"string1",
"packageValue":"string"
},
{
"packageName":"string2",
"packageValue":"string"
}
]
var packageNames = data.map(function(obj){
return obj.packageName;
})
console.log(packageNames)
You can use filter function and add to array only when this key exists.
var arr = [];
data.filter(getValue)
function getValue(data){
if(data[packageName]){
arr.push(data[packageName])
}
}
You can add an if statement to check the key and then push it to an array.
for(var i = 0; i< data.length; i++){
for (var property in data[i]) {
if (data[i].hasOwnProperty(property)) {
console.log(property);
console.log(data[i][property]);
}
}
}

Get value from json string using key's value [duplicate]

This question already has answers here:
How to find an appropriate object in array by one of its properties
(3 answers)
Closed 6 years ago.
Hi I have a json string
"{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}"
I want to check ConfigValue of ConfigName "CurrentTime".
Currently I am accessing it by below code
var d = JSON.parse(data).data;
d[2].ConfigValue
but sometimes the json string will be
"{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}"
according to above string now if i want to access "CurrentTime"
I will have to write below code
var d = JSON.parse(data).data;
d[1].ConfigValue
So can anyone tell how to access it? Because the array may change anytime so I cannot hardcode the array index like that.
You can run a loop and check the value of ConfigName. Below is the code
var data = '{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}';
var d = JSON.parse(data).data;
for(var i=0; i<d.length; i++)
{
if(d[i].ConfigName === 'CurrentTime')
{
alert(d[i].ConfigValue); //Do stuff with the value.
}
}
You have same quotes inside and outside string without escaping. But maybe it takes place only in question texts.
In this case You need to check every item like this:
for (var i in d) {
if (d[i].Id == 0) {
alert(d[i].ConfigName);
}
}
You can try this:
var k = {"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}
var result = $(jQuery.parseJSON(JSON.stringify(k))).each(function() {
var configName = this.ConfigName;
var configValue = this.ConfigValue;
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You first need to find the object in the array with "ConfigValue" equal to "CurrentTime". Once you have this object, you can simply access its "CongigValue" property.
var json1 = {"data":
[
{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}
]
};
var json2 = {"data":
[
{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}
]
};
var currentTime = findCurrentTime( json1 );
console.log( "currentTime: " + currentTime );
var currentTime = findCurrentTime( json2 );
console.log( "currentTime: " + currentTime );
function findCurrentTime( jsonObj )
{
var filteredArray = jsonObj.data.filter(function(element){
return element.ConfigName === "CurrentTime";
});//filter()
if( filteredArray.length > 0 )
return filteredArray[0].ConfigValue;
return false;
}//findCurrentTime()

Access to a certain part of JSON data with jQuery

So i have this JSON:
{
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
}
I just want to access to the fields names
id_u,_nombre_usuario,apellido_paterno_usuario
And then, create an array with that info.
How can i do that?
Thanks guys
Do this way :
var keyValuePair = {
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
};
var arr =new Array();
for (key in keyValuePair){
arr.push(key); // for keys
// arr.push(keyValuePair[key]); // for values
}
Use .each() to parse JSON.
Try this:
var keyArray = [];
var a = {
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
};
$.each(a,function(i,v){
keyArray.push(i); // i is json key and v is json value.
});
console.log(keyArray);
DEMO
Object.keys(jsonObject) is enough.

Get value from json object without count the array number

This is my json object i want to get alert it without the array order like[0], [1].
var jsononj = {
"objnew" :
[{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
] };
}
var newtest = jsononj.objnew[0].testarry;
alert(newtest);
i want to alert without [0]. how to i achieve this
I think this is what you're looking for:
var i;
for (i = 0; i < jsonobj.objnew.length; i++) {
if (jsonobj.objnew[i].testarry) {
alert(jsonobj.objnew[i].testarry);
}
}
This is just stupid but I removed the [0]
var jsononj = {
"objnew" : [
{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
]
};
var a = jsononj.objnew.shift();
alert(a.testarry);
jsononj.objnew.unshift(a);
That's not JSON, that's a Javascript object. JSON is a text format for representing data.
If you want to look for an object with a specific property, loop through the objects in the array and check for it:
var newtest = null;
for (var i = 0; i < jsononj.objnew.length; i++) {
var obj = jsononj.objnew[i];
if (obj.hasOwnProperty('testarry') {
newtest = obj.testarry;
break;
}
}
if (newtest != null) {
// found one
}
doing a var firstOne = jsononj.objnew[0];
but if you simply don't like the [0] through your lines, extend the Array prototype
Array.prototype.first = function () {
return this[0];
};
var newtest = jsononj.objnew.first().testarry;
alert(newtest);
more info at First element in array - jQuery

Categories

Resources