JSON – 使用变量名称搜索键(未知)

总JSON noob在这里。 我试图循环一些JSON从对象内的数组中取出第一个图像,经过4个小时后,我决定我可能需要一些帮助。

我能够从我知道密钥的对象中提取出我需要的每个值,但是我有一些数据具有非一致的密钥名称,我需要基本上通过寻找部分匹配进行迭代然后拉出第一个这些结果。

未知元素的Json结构的结构如下:

"custom_fields": { "content_0_subheading": [ "Title text" ], "content_1_text": [ "Some text" ], "content_2_image": [ [ "http://sofzh.miximages.com/javascript/wellbeing-260x130.jpg", 260, 130, true ] ], "content_2_caption": [ "" ] } 

我所追求的是这种情况下的content_2_image,但是在另一个条目中,我知道的所有内容都可能是content_20_image(有很多数据被拉出)。

任何关于循环通过这些未知键的最佳方法的想法,寻找键中的’_image’的部分匹配,将非常感激。

谢谢!

您不能仅使用部分匹配搜索每个字段,因此您必须遍历每个字段,然后检查匹配的字段名称。 尝试这样的事情:

 var json = { "content_0_subheading": [ "Title text" ], "content_1_text": [ "Some text" ], "content_2_image": [ [ "http://sofzh.miximages.com/javascript/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对象的键(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])

希望这可以帮助!

你可以使用for ... in

 for (key in object) { // check match & do stuff } 
 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