[javascript] 중첩 된 JSON 객체-모든 것에 배열을 사용해야합니까?

JSON에 중첩 된 객체를 가질 수있는 방법이 있습니까? 그래서 모든 것에서 배열을 만들 필요가 없습니까? 내 개체를 오류없이 구문 분석하려면 다음과 같은 구조가 필요한 것 같습니다.

{"data":[{"stuff":[
    {"onetype":[
        {"id":1,"name":"John Doe"},
        {"id":2,"name":"Don Joeh"}
    ]},
    {"othertype":[
        {"id":2,"company":"ACME"}
    ]}]
},{"otherstuff":[
    {"thing":
        [[1,42],[2,2]]
    }]
}]}

이 개체를 “result”라는 변수로 가져 오면 다음과 같이 중첩 된 개체에 액세스해야합니다.

result.data[0].stuff[0].onetype[0]

result.data[1].otherstuff[0].thing[0]

가능한 한 내가 선호하는 것은 서투르고 중복되는 것 같습니다.

result.stuff.onetype[0]

result.otherstuff.thing

그러나 모든 것이 배열 일 때 어떻게 직접 객체 키를 사용할 수 있습니까? 혼란스럽고 교육받지 못한 내 마음에는 다음과 같은 것이 더 적절 해 보일 것입니다.

{"data":
    {"stuff":
        {"onetype":[
            {"id":1,"name": ""},
            {"id":2,"name": ""}
        ]}
        {"othertype":[
            {"id":2,"xyz": [-2,0,2],"n":"Crab Nebula","t":0,"c":0,"d":5}
        ]}
    }
    {"otherstuff":
        {"thing":
            [[1,42],[2,2]]
        }
    }
}

나는 아마도 여기서 근본적인 것을 오해했지만, 두 번째 스타일 객체를 받아들이 기 위해 jQuery 파서 (jQuery 1.4에서 사용하는 네이티브 FF 파서도 아님)를 얻을 수 없습니다. 누구든지 나를 깨달을 수 있다면 감사하겠습니다!



답변

배열을 사용할 필요가 없습니다.

JSON 값은 배열, 객체 또는 기본 (숫자 또는 문자열) 일 수 있습니다.

다음과 같이 JSON을 작성할 수 있습니다.

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

다음과 같이 사용할 수 있습니다.

obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1]  //thing is a nested array or a 2-by-2 matrix.
                            //I'm not sure whether you intended to do that.


답변

모든 개체는 부모 개체 내에서 이름이 지정되어야합니다.

{ "data": {
    "stuff": {
        "onetype": [
            { "id": 1, "name": "" },
            { "id": 2, "name": "" }
        ],
        "othertype": [
            { "id": 2, "xyz": [-2, 0, 2], "n": "Crab Nebula", "t": 0, "c": 0, "d": 5 }
        ]
    },
    "otherstuff": {
        "thing":
            [[1, 42], [2, 2]]
    }
}
}

따라서 다음과 같은 객체를 선언 할 수 없습니다.

var obj = {property1, property2};

그건 그래야만 해

var obj = {property1: 'value', property2: 'value'};


답변

jSON 데이터 내에 중복 된 중첩 배열이 너무 많지만 정보를 검색 할 수 있습니다. 다른 사람들처럼 당신이 그것을 정리하고 싶을 수도 있다고 말했지만.

마지막 배열까지 다른 each () 내에서 each () 랩을 사용하십시오.

위해 result.data[0].stuff[0].onetype[0]에서 jQuery를 다음을 수행 할 수 있습니다 :

`

$.each(data.result.data, function(index0, v) {
    $.each(v, function (index1, w) {
        $.each(w, function (index2, x) {
            alert(x.id);
        });
    });

});

`


답변