7

我正在尝试使用 Google Refine 从数据科学工具包坐标 2 政治 API 的结果中提取特定元素。

这是示例单元#1:

[{"politics":[
 {"type":"admin2","friendly_type":"country","code":"usa","name":"United States"},
 {"type":"admin6","friendly_type":"county","code":"55_025","name":"Dane"},
 {"type":"constituency","friendly_type":"constituency","code":"55_02","name":"Second district, WI"},
 {"type":"admin5","friendly_type":"city","code":"55_48000","name":"Madison"},
 {"type":"admin5","friendly_type":"city","code":"55_53675","name":"Monona"},
 {"type":"admin4","friendly_type":"state","code":"us55","name":"Wisconsin"},
 {"type":"neighborhood","friendly_type":"neighborhood","code":"Eastmorland|Madison|WI","name":"Eastmorland"}
 ],"location":{"longitude":"-89.3259404","latitude":"43.0859191"}}]

我使用此 GREL 语法在此列的基础上添加了一个列,以提取 Dane 县:

value.parseJson()[0]["politics"][1]["name"]

但是当我到达 Sample Cell #2 时,语法不再有效,因为 JSON 结果有点不同:

[{"politics":[
 {"type":"admin2","friendly_type":"country","code":"usa","name":"United States"},
 {"type":"constituency","friendly_type":"constituency","code":"55_05","name":"Fifth district, WI"},
 {"type":"admin4","friendly_type":"state","code":"us55","name":"Wisconsin"},
 {"type":"admin6","friendly_type":"county","code":"55_079","name":"Milwaukee"},
 {"type":"admin5","friendly_type":"city","code":"55_84675","name":"Wauwatosa"},
 {"type":"constituency","friendly_type":"constituency","code":"55_04","name":"Fourth district, WI"}
 ],"location":{"longitude":"-88.0075875","latitude":"43.0494572"}}]

是否有某种方法可以对 JSON 进行排序或对我的语法进行短语化,以便在任何一种情况下都能找到县?

更新

这是神奇的 GREL,它允许我按名称查找 JSON 字符串中的元素,而不仅仅是位置:

filter(value.parseJson()[0]["politics"], item, item["type"]=="admin6")[0]["name"]
4

1 回答 1

6

名为的字段politics是一个数组,您可以返回:

value.parseJson()[0]["politics"]

该数组的一个元素与县相关联(它的friendly_type字段为“县”)。因此,您需要过滤该politics字段以找到friendly_type属于县的字段,如下所示:

filter(value.parseJson()[0]["politics"], item, item["friendly_type"]=="county")

这将返回一个包含一个元素的数组。您想name从那个元素中取出该字段,因此您需要提取name第零个数组元素的 ,从而形成完整的表达式:

filter(value.parseJson()[0]["politics"], item, item["friendly_type"]=="county")[0]["name"]
于 2012-04-25T14:38:25.193 回答