JSON - 搜索具有变量名称(未知)的键

JSON - searching through keys with variable names (unknown)

本文关键字:未知 的键 变量名 搜索 JSON      更新时间:2023-09-26

这里的 JSON 菜鸟总数。我正在尝试循环使用一些 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": [
      ""
        ]
}

我所追求的是在这种情况下的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!
        }
    }
}

基本上,我们正在做的是:

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])

希望这有帮助!

你可以使用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