javascript 查找json字符串的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10648172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find length of json string
提问by ghanshyam.mirani
I have following Jsonstring
我有以下 Jsonstring
var j = { "name": "John" };
alert(j.length);
it alerts : undefined, How can i find the length of json Array object??
它提醒:未定义,我如何找到 json 数组对象的长度?
Thanks
谢谢
回答by Bergi
Lets start with the json string:
让我们从 json 字符串开始:
var jsonString = '{"name":"John"}';
you can easily determine its length:
您可以轻松确定其长度:
alert("The string has "+jsonString.length+" characters"); // will alert 15
Then parse it to an object:
然后将其解析为一个对象:
var jsonObject = JSON.parse(jsonString);
A JavaScript Object
is notan Array
and has no length. If you want to know how many properties it has, you will need to count them:
一个JavaScript不是一个,没有长度。如果你想知道它有多少属性,你需要计算它们:Object
Array
var propertyNames = Object.keys(jsonObject);
alert("There are "+propertyNames.length+" properties in the object"); // will alert 1
If Object.keys
, the function to get an Array
with the (own) property names from an Object
, is not available in your environment (older browsers etc.), you will need to count manually:
如果Object.keys
,从 an 中获取Array
(自己的)属性名称的函数Object
在您的环境(旧浏览器等)中不可用,您将需要手动计数:
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
回答by Ryan
function getObjectSize(o) {
var c = 0;
for (var k in o)
if (o.hasOwnProperty(k)) ++c;
return c;
}
var j = { "name": "John" };
alert(getObjectSize(j)); // 1
回答by Jamie Dixon
Another way of doing this is to use the later JSON.stringify
method which will give you an object (a string) on which you can use the length
property:
另一种方法是使用后面的JSON.stringify
方法,该方法将为您提供一个对象(一个字符串),您可以在该对象上使用该length
属性:
var x = JSON.stringify({ "name" : "John" });
alert(x.length);
回答by xdazz
There is no json Array object in javascrit. j
is just an object in javascript.
javascrit 中没有 json Array 对象。j
只是 javascript 中的一个对象。
If you means the number of properties the object has(exclude the prototype's), you could count it by the below way:
如果您的意思是对象具有的属性数量(不包括原型),您可以通过以下方式计算它:
var length = 0;
for (var k in j) {
if (j.hasOwnProperty(k)) {
length++;
}
}
alert(length);