获取json对象的大小

时间:2011-07-20 01:44:14

标签: javascript json

我有一个由AJAX请求返回的json对象,我在使用.length时遇到了一些问题,因为它一直在返回undefined。只是想知道我是否正确使用它:

console.log(data.length);
console.log(data.phones.length);

他们都返回undefined,即使它们是有效的对象。

更新
返回的JSON对象示例:

{"reqStatus":true,"phones":{"one":{"number":"XXXXXXXXXX","type":"mobile"},"two":{"number":"XXXXXXXXXX","type":"mobile"}}}

8 个答案:

答案 0 :(得分:482)

您可以使用类似

的内容
<script type="text/javascript">

  var myObject = {'name':'Kasun', 'address':'columbo','age': '29'}

  var count = Object.keys(myObject).length;
  console.log(count);
</script>

答案 1 :(得分:54)

您的问题是您的手机对象没有长度属性(除非您在返回的JSON中的某个位置定义它),因为对象与数组不同,即使用作关联数组也是如此。如果手机对象是一个数组,它将有一个长度。你有两个选择(可能更多)。

  1. 更改您的JSON结构(假设这是可能的),以便'手机'变为

    "phones":[{"number":"XXXXXXXXXX","type":"mobile"},{"number":"XXXXXXXXXX","type":"mobile"}]
    

    (请注意,每个手机没有字编号标识符,因为它们在0索引数组中返回)。在此回复中,phones.length将有效。

  2. 遍历手机对象中包含的对象并随时计算,例如。

    var key, count = 0;
    for(key in data.phones) {
      if(data.phones.hasOwnProperty(key)) {
        count++;
      }
    }
    
  3. 如果您只定位新浏览器,则选项2可能看起来像this

答案 2 :(得分:27)

考虑使用underscore.js。它可以让你检查尺寸,如:

var data = {one : 1, two : 2, three : 3};
_.size(data);
//=> 3
_.keys(data);
//=> ["one", "two", "three"]
_.keys(data).length;
//=> 3

答案 3 :(得分:19)

您无需更改JSON格式。

取代:

console.log(data.phones.length);

使用:

console.log( Object.keys( data.phones ).length ) ;

答案 4 :(得分:16)

var json=[{"id":"431","code":"0.85.PSFR01215","price":"2457.77","volume":"23.0","total":"565.29"},{"id":"430","code":"0.85.PSFR00608","price":"1752.45","volume":"4.0","total":"70.1"},{"id":"429","code":"0.84.SMAB00060","price":"4147.5","volume":"2.0","total":"82.95"},{"id":"428","code":"0.84.SMAB00050","price":"4077.5","volume":"3.0","total":"122.32"}] 
var obj = JSON.parse(json);
var length = Object.keys(obj).length; //you get length json result 4

答案 5 :(得分:0)

尝试

$.parseJSON(data).length

答案 6 :(得分:-2)

使用这个

#include <iostream>
#include <vector>
#include <stack>
using namespace std;

class Graph{
        public:
            vector<int> adjList[10001];
            void addEdge(int u,int v){
                adjList[u].push_back(v);
                adjList[v].push_back(u);
            }
};

bool dfs(Graph graph, int n){
    vector<int> neighbors;
    int curr,parent;
    bool visited[10001] = {0};
    stack<int> s;
    //Depth First Search
    s.push(1);
    parent = 0;
    while(!s.empty()){
        curr = s.top();
        neighbors = graph.adjList[curr];
        s.pop();
        //If current is unvisited
        if(visited[curr] == false){
            for(int j=0; j<neighbors.size(); j++){
                //If node connected to itself, then cycle exists
                if(neighbors[j] == curr){
                    return false;;
                }
                else if(visited[neighbors[j]] == false){
                    s.push(neighbors[j]);
                }
                //If the neighbor is already visited, and it is not a parent, then cycle is detected
                else if(visited[neighbors[j]] == true && neighbors[j] != parent){
                    return false;
                }
            }
            //Mark as visited
            visited[curr] = true;
            parent = curr;
        }
    }
    //Checking if graph is fully connected
    for(int i=1; i<=n; i++){
        if(visited[i] == false){
            return false;
        }
    }
    //Only if there are no cycles, and it's fully connected, it's a tree
    return true;
}

int main() {
    int m,n,u,v;
    cin>>n>>m;
    Graph graph = Graph();
    //Build the graph
    for(int edge=0; edge<m; edge++){
        cin>>u>>v;
        graph.addEdge(u,v);
    }
    if(dfs(graph,n)){
        cout<<"YES"<<endl;
    }
    else{
        cout<<"NO"<<endl;
    }
    return 0;
}

//for getting length of object
 int length = jsonObject.length();

答案 7 :(得分:-5)

$(document).ready(function () {
    $('#count_my_data').click(function () {
        var count = 0;
        while (true) {
             try {
                var v1 = mydata[count].TechnologyId.toString();
                count = count + 1;
            }
            catch (e)
            { break; }
        }
        alert(count);
    });
});