jQuery 和 JSON 对象迭代
我目前正在尝试弄清楚如何迭代 JSON 响应中的所有对象。我的对象可能有无穷无尽的子对象,它们也可能有无穷无尽的子对象。
{
"obj1" : {
"obj1.1" : "test",
"obj1.2" : {
"obj1.1.1" : true,
"obj1.1.2" : "test2",
"obj1.1.3" : {
... // etc
}
}
}
}
我只是想知道是否有一个开箱即用的脚本可以处理此类对象?
I'm currently trying to figure out how can I iterate over all of the objects in an JSON response. My object may have endless sub objects and they may also have endless sub objects.
{
"obj1" : {
"obj1.1" : "test",
"obj1.2" : {
"obj1.1.1" : true,
"obj1.1.2" : "test2",
"obj1.1.3" : {
... // etc
}
}
}
}
I was just wondering if there is a out of the box script that can handle such kind of objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是一个小函数,可以跟踪您在树中行走的深度,并沿途停下来允许您执行操作(您没有指定您实际想要执行的操作或时间):
假设 obj 是您的 JSON,如上所述,这应该给您类似的内容(未测试):
Here's a little function that tracks the depth of your walk through the tree, with stops along the way to allow you to do perform an action (you didn't specify what you actually want to do, or when):
Assuming
obj
is your JSON as above, this should give you something like (not tested):您在问题中表示的不是 JSON,而是 JavaScript 对象文字。区别在于,一种是字符串,另一种是实际的文字对象,无需进一步转换即可在 JavaScript 中使用。
要遍历 JS 对象文字,请使用简单的递归 for 循环。为此,您不需要单独的库。
What you've represented in your question is not JSON, it's a JavaScript Object Literal. The difference is one is a string, and one is an actual literal object that can be used in JavaScript without further conversion.
To walk a JS Object Literal, use a simple recursive for loop. You don't need a separate library for that.
将 JSON 解析为对象后,您需要实现树遍历器(递归函数)来查找您感兴趣的特定值。
但是,JOrder 可能会为您提供很大帮助,它提供数据管理设施,这可以节省您编写树步行者的时间。并进行良好的、高性能的搜索和排序。
https://github.com/danstocker/jorder
Once you've parsed the JSON into an Object, You'll need to implement a tree-walker (a recursive function) to find particular values you are interested in.
However, JOrder will probably help you a great deal, it provides data management facilities, this saves you writing a tree-walker. and does a good, performant search and sort.
https://github.com/danstocker/jorder
jQuery JavaScirpt 库只有方法:
parseJSON() 方法 接受一个 JSON 字符串(其中是您从 JSON 请求中获得的内容)并返回一个 JavaScript 对象。从那里您可以像平常使用任何 JavaScript 对象一样访问数据。
The jQuery JavaScirpt library has just the method:
The parseJSON() method accepts a JSON string (which is what you would get from a JSON request) and returns a JavaScript object. From there you can access the data as you would normally with any JavaScript object.
我正在使用此代码片段来遍历 de json。基本上,当节点是一个对象时,我递归地调用相同的函数。希望您觉得它有用。
正如您所看到的,它需要 jQuery。不使用相同的想法也可以完成。
函数记录器(json)
{};
I am using this code snippet to walk through de json. Basically when the node is an object I call the same function recursively. Hope you find it useful.
It needs, as you can see, jQuery. It also can be done without using the same idea.
function recorrer(json)
{};