找到json字符串的长度

gha*_*ani 0 javascript json

我有以下Jsonstring

  var j = { "name": "John" };
            alert(j.length);
Run Code Online (Sandbox Code Playgroud)

它警告:undefined,我怎样才能找到json Array对象的长度?

谢谢

Ber*_*rgi 8

让我们从json字符串开始:

var jsonString = '{"name":"John"}';
Run Code Online (Sandbox Code Playgroud)

你可以很容易地确定它的长度:

alert("The string has "+jsonString.length+" characters"); // will alert 15
Run Code Online (Sandbox Code Playgroud)

然后将其解析为一个对象:

var jsonObject = JSON.parse(jsonString);
Run Code Online (Sandbox Code Playgroud)

JavaScript 不是一个没有长度的.如果您想知道它有多少属性,您需要计算它们:Object Array

var propertyNames = Object.keys(jsonObject);
alert("There are "+propertyNames.length+" properties in the object"); // will alert 1
Run Code Online (Sandbox Code Playgroud)

如果在您的环境(旧版浏览器等)中无法使用来自a的(自己的)属性名称Object.keys的函数,则需要手动计算:ArrayObject

var props = 0;
for (var key in jsonObject) {
    // if (j.hasOwnProperty(k))
    /* is only needed when your object would inherit other enumerable
       properties from a prototype object */
        props++;
}
alert("Iterated over "+props+" properties"); // will alert 1
Run Code Online (Sandbox Code Playgroud)