将此JSON转换为树并找到父级的路径

时间:2019-05-30 21:59:20

标签: json path tree parent

data= {
"saturn": [
        "planet",
        "american_car",
        "car"
    ],
    "american_car": [
        "car",
        "gas_driven_automobile"
    ],
    "planet": [
        "large_object",
        "celestial_body"
    ],
    "large_object": [],
    "gas_driven_automobile": [
        "gas_powered_road_vehicle",
        "car"
    ],
    "car": [
        "vehicle",
        "motor_vehicle"
    ],
"vehicle": [],
"motor_vehicle": [],
"gas_powered_road_vehicle": [],
"celestial_body": []
};

我需要编写一种算法,在该算法中,如果输入“土星”,则需要获取从土星到其他父母的所有可能路径。例如

saturn ->planet ->large_object  
saturn ->american_car->car->vehicle
saturn ->american_car->car->motor_vehicle
saturn ->american_car->gas_driven_automobile->gas_powered_road_vehicle
saturn ->american_car->gas_driven_automobile->car->vehicle

以及所有其他可能的路径。

我正在考虑以某种方式将其转换为树,然后使用库来计算从子级到父级的路径。

编写算法时,无法弄清楚如何将其转换为树。

1 个答案:

答案 0 :(得分:0)

使用,您可以简单地定义一个递归函数:

def parents($key):
  if has($key)
  then if .[$key] == []  then [] else .[$key][] as $k | [$k] + parents($k) end
  else []
  end;

要使用它来产生“->”样式的输出,请使用-r命令行选项调用jq,然后像上面那样调用上述函数:

["saturn"] + parents("saturn")
| join(" -> ")

更经济

def lineages($key):
  [$key] + (lineages(.[$key][]) // []);


lineages("saturn") | join(" -> ")