如何访问特定 json 键的索引
How to access the index of a specific json key
我需要访问特定的键来捕获键为administrative_area_level_2或administrative_area_level_1[=27的节点信息=].
我目前正在按索引“1”或“2”访问。
但是如果 json 来自 Google Api Places 的结果有更多数据,这些索引将不正确。
有什么方法可以访问我想要捕获城市或州名称的特定密钥?
示例代码:
class Api {
pesquisar (String local) async{
http.Response response = await http.get(
URL_BASE + "?place_id=$local" +"&fields=name,address_component&key=" +KEY_PLACE
);
if( response.statusCode == HttpStatus.ok ){
Map<String, dynamic> dadosJson = json.decode( response.body );
print( "Data : " + dadosJson["result"]["address_components"][1]["short_name"].toString() );
print( "Data : " + dadosJson["result"]["address_components"][2]["short_name"].toString() );
} else {
}
}
}
你可以这样做:
List components = dadosJson["result"]["address_components"];
final item1 = components.firstWhere(
(item) => item["types"].contains("administrative_area_level_1"));
final item2 = components.firstWhere(
(item) => item["types"].contains("administrative_area_level_1"));
print(item1["short_name"]);
print(item2["short_name"]);
或
List components = dadosJson["result"]["address_components"];
final items = components
.where((item) =>
item["types"].contains("administrative_area_level_1") ||
item["types"].contains("administrative_area_level_2"))
.toList();
items.forEach((item) => print(item["short_name"]));
我建议您将 json 解析为对象模型,这样您就不必面对一些类型推断问题。
我需要访问特定的键来捕获键为administrative_area_level_2或administrative_area_level_1[=27的节点信息=].
我目前正在按索引“1”或“2”访问。
但是如果 json 来自 Google Api Places 的结果有更多数据,这些索引将不正确。
有什么方法可以访问我想要捕获城市或州名称的特定密钥?
示例代码:
class Api {
pesquisar (String local) async{
http.Response response = await http.get(
URL_BASE + "?place_id=$local" +"&fields=name,address_component&key=" +KEY_PLACE
);
if( response.statusCode == HttpStatus.ok ){
Map<String, dynamic> dadosJson = json.decode( response.body );
print( "Data : " + dadosJson["result"]["address_components"][1]["short_name"].toString() );
print( "Data : " + dadosJson["result"]["address_components"][2]["short_name"].toString() );
} else {
}
}
}
你可以这样做:
List components = dadosJson["result"]["address_components"];
final item1 = components.firstWhere(
(item) => item["types"].contains("administrative_area_level_1"));
final item2 = components.firstWhere(
(item) => item["types"].contains("administrative_area_level_1"));
print(item1["short_name"]);
print(item2["short_name"]);
或
List components = dadosJson["result"]["address_components"];
final items = components
.where((item) =>
item["types"].contains("administrative_area_level_1") ||
item["types"].contains("administrative_area_level_2"))
.toList();
items.forEach((item) => print(item["short_name"]));
我建议您将 json 解析为对象模型,这样您就不必面对一些类型推断问题。