Javascript JSON-搜索具有变量名的键(未知)
这里没有。我试图循环使用一些JSON,从对象内部的数组中提取第一个图像,经过4个小时的处理后,我决定可能需要一些帮助 我能够从我知道键的对象中提取我需要的每个值,但是我有一些数据具有不一致的键名,我需要基本上通过迭代寻找部分匹配,然后提取这些结果中的第一个 未知元素的Json结构如下所示:Javascript JSON-搜索具有变量名的键(未知),javascript,jquery,json,jsonp,Javascript,Jquery,Json,Jsonp,这里没有。我试图循环使用一些JSON,从对象内部的数组中提取第一个图像,经过4个小时的处理后,我决定可能需要一些帮助 我能够从我知道键的对象中提取我需要的每个值,但是我有一些数据具有不一致的键名,我需要基本上通过迭代寻找部分匹配,然后提取这些结果中的第一个 未知元素的Json结构如下所示: "custom_fields": { "content_0_subheading": [ "Title text" ], "content_1_text": [
"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": [
""
]
}
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!
}
}
}
在本例中,我想要的是content_2_图像,但在另一个条目中,据我所知,它可能是content_20_图像(正在提取大量数据)
任何关于循环使用这些未知键以查找键中“_image”部分匹配的最佳方法的想法都将非常感谢
谢谢 您可以使用
来。。。在
for (key in object) {
// check match & do stuff
}
您不能只搜索每个部分匹配的字段,因此您必须遍历每个字段,然后检查匹配的字段名。试着这样做:
"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": [
""
]
}
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!
}
}
}
基本上,我们正在做的是:
1) 循环通过json对象的键for(json中的var键)
2) 确保json具有该属性,并且我们不会访问不需要的键if(json.hasOwnProperty(key))
3) 检查键是否与正则表达式匹配/content[0-9]+\u image/
3a)基本上,测试它是否匹配内容\u任何数字\u图像
,其中任何数字
至少等于一位或多位
4) 请随意使用这些数据console.log(json[key])
希望这有帮助 您是控制JSON结构还是这是某种API调用响应?
var json = JSON.parse(YOUR_JSON_STRING).custom_fields, //Fetch your JSON
image; //Pre-declare image
for(key in json){ //Search each key in your object
if(key.indexOf("image") != -1){ //If the index contains "image"
image = json[key]; //Then image is set to your image array
break; //Exit the loop
}
}
/*
image[0] //the URL
image[1] //the width
image[2] //the height
image[3] //your boolean