gpt4 book ai didi

javascript - 获取 JSON 中的对象总数,但 Javascript Object.keys().length 返回未定义

转载 作者:行者123 更新时间:2023-12-03 02:32:44 26 4
gpt4 key购买 nike

我正在尝试从 REST 服务返回的 JSON 对象中获取值。当我尝试获取“行”或“记录”的数量(而不是键的数量)时,我不断地得到 undefined使用Object.keys(json).length时.

我已经审查并尝试了这些帖子中的一些答案:

Length of a JavaScript object

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 对象的长度为 1。如果返回更多,该数字还会上升。

这是代码的输出:

json: [object Object]
json.length: undefined
propertyNames.length: undefined
jsonLength: undefined
undefined is not a number
jsonLength = 0

感谢任何帮助。

最佳答案

Object.keys(json) 返回一个数组,因此它的 .length 是一个数字。

您正在尝试获取数字的.length,这是没有意义的。

关于javascript - 获取 JSON 中的对象总数,但 Javascript Object.keys().length 返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48668683/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com