Ste*_*ese 5 javascript jquery json jsonp
总JSON noob在这里.我正试图循环一些JSON从对象内部的数组中取出第一个图像,经过4个小时后,我决定我可能需要一些帮助.
我能够从我知道密钥的对象中提取出我需要的每个值,但是我有一些数据具有非一致的密钥名称,我需要基本上通过查找部分匹配进行迭代然后拉出第一个这些结果.
未知元素的Json结构的结构如下:
"custom_fields": {
"content_0_subheading": [
"Title text"
],
"content_1_text": [
"Some text"
],
"content_2_image": [
[
"http://staging.livelivelyblog.assemblo.com/wp-content/uploads/2013/09/wellbeing-260x130.jpg",
260,
130,
true
]
],
"content_2_caption": [
""
]
}
Run Code Online (Sandbox Code Playgroud)
我所追求的是这种情况下的content_2_image,但在另一个条目中,我知道的所有内容都可能是content_20_image(有很多数据被拉出).
任何关于循环通过这些未知键的最佳方法的想法,在键中的'_image'上寻找部分匹配,将非常感激.
谢谢!
您不能只搜索具有部分匹配的每个字段,因此您必须遍历每个字段,然后检查匹配的字段名称.尝试这样的事情:
var json = {
"content_0_subheading": [
"Title text"
],
"content_1_text": [
"Some text"
],
"content_2_image": [
[
"http://staging.livelivelyblog.assemblo.com/wp-content/uploads/2013/09/wellbeing-260x130.jpg",
260,
130,
true
]
],
"content_2_caption": [
""
]
}
for (var key in json) {
if (json.hasOwnProperty(key)) {
if (/content_[0-9]+_image/.test(key)) {
console.log('match!', json[key]); // do stuff here!
}
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,我们正在做的是:
1)循环通过json对象的键 for (var key in json)
2)确保json具有属性,并且我们不访问我们不想要的密钥 if (json.hasOwnProperty(key))
3)检查密钥是否与正则表达式匹配 /content_[0-9]+_image/
图3a)基本上,如果它匹配测试content_ANY NUMBERS_image,其中ANY NUMBERS是等于至少一个数位或更多
4)请随意使用该数据 console.log(json[key])
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
23937 次 |
| 最近记录: |