我试图从返回的JSON对象中获取REST服务的值。当我试图得到"行数#34;或"记录" - 不是键数 - 我在使用undefined
时不断获得Object.keys(json).length
。
我已经在这些帖子中审核并尝试了一些答案:
Get total number of items on Json object?
以下是我正在使用的代码:
$.getJSON(finalURL, function(json) {
console.log("json: " + json);
console.log("json.length: " + json.length);
var propertyNames = Object.keys(json).length;
console.log("propertyNames.length: " + propertyNames.length);
var jsonLength = propertyNames.length;
console.log("jsonLength: " + jsonLength);
if (isNaN(jsonLength)) {
console.log(jsonLength + " is not a number");
} else {
console.log(jsonLength + " is a number");
}
if (jsonLength > 0) {
console.log("jsonLength > 0");
} else {
console.log("jsonLength = 0");
}
});
这是返回的JSON:
{"id":1,"providerName":"Acme","providerID":"12343","providerLegacyID":"832940","contactName":"John Doe","contactEmail":"jdoe@this.eml","contactPhone":"3035551212","address1":"5999 Second Street","address2":"","city":"Denver","state":"CO","zip":"80203","providerKey":"0be32d8057924e718a8b6b4186254756","userKeys":null,"approved":null,"active":null,"createdBy":"Dan Zeller","createdByKey":"c6f4cf6a47a44092a3655420bd4a3f26","createdByRole":"ADMIN","createdDate":1517927130501,"updatedBy":null,"updatedByKey":null,"updatedByRole":null,"updatedDate":null,"removedBy":null,"removedByKey":null,"removedByRole":null,"removedByDate":null,"restoredBy":null,"restoredByKey":null,"restoredByRole":null,"restoredByDate":null}
所以我希望JSON对象的长度与上面的JSON一样。如果返回更多,那么这个数字就会增加。
以下是代码的输出:
json: [object Object]
json.length: undefined
propertyNames.length: undefined
jsonLength: undefined
undefined is not a number
jsonLength = 0
感谢任何帮助。
答案 0 :(得分:1)
Object.keys(json)
返回一个数组,因此其.length
是一个数字。
你正试图获得一个数字的.length
,这没有任何意义。
答案 1 :(得分:0)
你可以使用这样的想法:
var myObject = {"id":1,"providerName":"Acme","providerID":"12343","providerLegacyID":"832940","contactName":"John Doe","contactEmail":"jdoe@this.eml","contactPhone":"3035551212","address1":"5999 Second Street","address2":"","city":"Denver","state":"CO","zip":"80203","providerKey":"0be32d8057924e718a8b6b4186254756","userKeys":null,"approved":null,"active":null,"createdBy":"Dan Zeller","createdByKey":"c6f4cf6a47a44092a3655420bd4a3f26","createdByRole":"ADMIN","createdDate":1517927130501,"updatedBy":null,"updatedByKey":null,"updatedByRole":null,"updatedDate":null,"removedBy":null,"removedByKey":null,"removedByRole":null,"removedByDate":null,"restoredBy":null,"restoredByKey":null,"restoredByRole":null,"restoredByDate":null};
var count = Object.keys(myObject).length;
console.log(count);