如何在javascript中获取json编码数组的长度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19516871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:56:23  来源:igfitidea点击:

how to get length of json encoded array in javascript?

javascriptarraysjson

提问by DS9

I have a json encoded array like this:

我有一个像这样的 json 编码数组:

{
  "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

(1) 如何求这个数组的长度? //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]]}

(2) 如何使用它的价值?
//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 :

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

回答by Pith

Your JSON is not an array, but an object. If you want it to be an array, it should be something like this:

您的 JSON 不是数组,而是一个对象。如果你希望它是一个数组,它应该是这样的:

[
  "{\"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:

然后,您可以获得一个 javascript 数组,如下所示:

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_encodemethod, see this related question.

编辑:为了使用 PHPjson_encode方法获得真正的 JSON 数组,请参阅此相关问题

With this modification you will be able to use all the possibilities of JS array without workaround.

通过此修改,您将能够使用 JS 数组的所有可能性而无需解决方法。

回答by Halcyon

Objects in JavaScript don't have a .lengthproperty like Arrays do.

JavaScript 中的对象没有.length像数组那样的属性。

In ES5 you can do: Object.keys({}).length; // 0

在 ES5 中,您可以执行以下操作: Object.keys({}).length; // 0

The other solution would be to loop over all the properties of your object with a for .. inloop and count.

另一种解决方案是使用for .. in循环和计数循环遍历对象的所有属性。

回答by Hasib Hasan Arnab

You can use the following code. It will produce your desired output 3

您可以使用以下代码。它将产生您想要的输出 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));

回答by Kippie

For your first question, you should use Object.keys(item).length

对于您的第一个问题,您应该使用 Object.keys(item).length

To get the values of your object, you should iterate over it with a forloop:

要获取对象的值,您应该使用循环对其进行迭代for

for(var key in item) { var val = item[key]; }

for(var key in item) { var val = item[key]; }

回答by bhb

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

alert(count);

Using jQuery

使用 jQuery

$(json).each(function() { count++; alert(this.start.lat); }); 
alert(count);