JSON数据检索:如何获取Matches Played与Score对应的值?
如何检索嵌套结构中的指定键值
嘿,我来帮你搞定这个数据检索的问题!首先得提一句,你给出的结构更偏向Objective-C里的数组嵌套字典格式,如果转换成标准JSON格式,应该是这样的:
[ {"key": "Matches Played", "value": 764}, {"key": "Score", "value": "126,830"} ]
下面我会用几种常见编程语言演示如何获取Matches Played和Score对应的值:
JavaScript 实现
我们可以用数组的find()方法定位到目标项,再提取对应的value。如果担心找不到目标键的情况,可以用可选链操作符避免报错:
const lifeTimeStats = [ { key: "Matches Played", value: 764 }, { key: "Score", value: "126,830" } ]; // 获取Matches Played的值 const matchesPlayed = lifeTimeStats.find(item => item.key === "Matches Played")?.value; console.log(matchesPlayed); // 输出 764 // 获取Score的值 const score = lifeTimeStats.find(item => item.key === "Score")?.value; console.log(score); // 输出 126,830
Python 实现
可以用生成器表达式配合next()函数快速找到目标值,同时也可以处理找不到键的异常情况:
lifeTimeStats = [ {"key": "Matches Played", "value": 764}, {"key": "Score", "value": "126,830"} ] # 获取Matches Played的值,找不到时返回默认值None matches_played = next((item["value"] for item in lifeTimeStats if item["key"] == "Matches Played"), None) print(matches_played) # 输出 764 # 获取Score的值 score = next((item["value"] for item in lifeTimeStats if item["key"] == "Score"), None) print(score) # 输出 126,830
Objective-C 实现
因为你给出的原始结构很像OC的写法,这里也提供对应的实现方式,通过遍历数组来匹配目标键:
NSArray *lifeTimeStats = @[ @{@"key": @"Matches Played", @"value": @764}, @{@"key": @"Score", @"value": @"126,830"} ]; NSNumber *matchesPlayed = nil; NSString *score = nil; for (NSDictionary *item in lifeTimeStats) { NSString *currentKey = item[@"key"]; if ([currentKey isEqualToString:@"Matches Played"]) { matchesPlayed = item[@"value"]; } else if ([currentKey isEqualToString:@"Score"]) { score = item[@"value"]; } } NSLog(@"Matches Played: %@", matchesPlayed); // 输出 764 NSLog(@"Score: %@", score); // 输出 126,830
小提示
如果你的数据量很大,或者需要频繁检索不同的键,建议先把这个数组转换成一个以key为键、value为值的扁平字典,这样后续的检索会更高效。比如在JavaScript里可以用Object.fromEntries():
const statsMap = Object.fromEntries(lifeTimeStats.map(item => [item.key, item.value])); console.log(statsMap["Matches Played"]); // 764 console.log(statsMap["Score"]); // 126,830
内容的提问来源于stack exchange,提问作者Dani Kemper
相关产品推荐
相关产品推荐

