使用JavaScript进行JSON解析的最佳方法 [英] Best way to JSON parsing using JavaScript

查看:77
本文介绍了使用JavaScript进行JSON解析的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:
JavaScript对象的长度(即,关联数组)

我有以下格式的JSON

I have JSON in the following format

[{"student":{"name" : "ABCD",
        "age":8,
        }
    "user":{ "firstName":"ABCD",
            "age": 9,
        }
        },
   {"student":{"name" : "XCYS",
        "age":10,
        }
    "user":{ "firstName":"GGG",
            "age": 11,
        }
},]

我尝试使用(数据.student [i] .length),这不起作用(只是看看对象的长度是多少),我也试过(data.user [i] )无济于事。

I tried using (data.student[i].length), which did not work (just to see what the length of the object is), and I also tried (data.user[i]) to no avail.

我基本上对如何获得JSON中某个对象的长度非常困惑,以及我如何可以有效地显示它。我该怎么做?

I am basically very confused on how I can get the length of one of the objects in the JSON and how I can effectively display it. How can I do this?

推荐答案

您的问题中的内容不能解析为有效JSON,因为所有密钥都需要包装在引号中(所以你应该age:11 而不是年龄:11 )。对象中的所有键/值对应以逗号分隔(因此您应该firstName:GGG,age:11 而不是firstName:GGGage:11 。外部数组中也有一个逗号逗号。

The content in your questions doesn't parse as valid JSON as all keys need to be wrapped in quotes (so you should have "age": 11 instead of age: 11). All key/value pairs in an object should be separated by a comma (so you should have "firstName": "GGG", "age": 11 instead of "firstName": "GGG" "age": 11. You also have a trailing comma in the outer array.

所以只要你有有效的JSON,你应该能够在比IE7更新的所有浏览器中使用 JSON.parse(data)将字符串转换为实际的对象。一个对象,你可以使用:

So long as you have valid JSON, you should be able to use JSON.parse(data) in all browsers newer than IE7 to convert the string into an actual object. Once parsed into an object, you can use:

var data = "your JSON string";
var object = JSON.parse(data);

console.log(object.length); // the number of objects in the array
console.log(object[0].student.name; // the name of the first student

如果您支持IE7及更早版本的浏览器,请查看Douglas Crockford的JSON polyfill: https://github.com/douglascrockford/JSON-js

If you are supporting browsers IE7 and older, check out Douglas Crockford's JSON polyfill: https://github.com/douglascrockford/JSON-js

这篇关于使用JavaScript进行JSON解析的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆