json 这对'jq'来说甚至是可能的吗?

yrdbyhpb  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(126)

我有一些JSON数据,如下所示

[ 
   {Key: "fruits/red/apple", Value: "Red apples"}, 
   {Key:"fruits/green/lime", Value: "Green Limes"}, 
   {Key: "fruits/blue/berries/blueberry", Value: "Blue Berries"}, 
   {Key: "vegetables/red/tomato", Value: "Red Tomatoes"}, 
   {Key: "vegetables/green/cucumber", Value: "Green Cucumbers"} 
]

我尝试将数据提取到嵌套的JSON树结构中,如

{
  "fruits": {
    "id": 1,
    "name": "fruits",
    "children": [
       { 
          "id": 2, 
          "name": "red", 
          "path": 1.2, 
          "children": [ { "id": 3, "name": "apple", "path": 1.2.3 } ]
       },
       { 
          "id: 4, 
          "name": "green",
          "path": 1.4, 
          "children": [ {"id": 5, "name": "lime", "path": 1.4.5} ]
       },
       { 
          "id: 6, 
          "name": "blue", 
          "path": 1.6, 
          "children": [ {"id": 7, "name": "berries", "path": 1.6.7, "children": [{...}] } ] 
       } 
    ]
  },
  "vegetables": {...}
}

我是jq新手,有这样的东西,它给了我一个数据级别,但是我不知道如何运行计数器和递归

[ .[] |  { name: .Key, description: .Value, children: ( [.Key | split("/")] | .[0] | to_entries ) } ]

感谢你的指点。

wnrlj8wa

wnrlj8wa1#

所需的输出不是JSON,并且很难生成那些非数字路径(例如1.2.3),显然可以添加引号使其成为字符串,但选择更标准或更方便的路径表示会更好。
除此之外,您可以放心,jq能够胜任这项任务,尽管它通常需要一些编程方面的专业知识,或者至少需要熟练使用jq。

相关问题