简体   繁体   English

Json 使用 JQ 提取带有索引的数组属性

[英]Json extract Array property with index using JQ

I got a Json which is basically a array but with a weird format that i can not change.我得到了一个 Json,它基本上是一个数组,但格式很奇怪,我无法更改。 Is there any way that i can get with JQ the url by searching for the name, like this?有什么方法可以通过搜索名称来获得 JQ url,就像这样?

{
    "servers": {
        "servers[0].name": "abc",
        "servers[0].url": "www.abc.test.com",
        "servers[1].name": "xyz",
        "servers[1].url": "www.xyz.test.com"
    }
}
jq -r  '.servers | select(.name=="abc") | .url'

 

Assuming the "=" can be naively changed to ":":假设“=”可以天真地更改为“:”:

sed 's/ = /: /' | jq '
  .servers
  | keys_unsorted[] as $k
  | select(.[$k] == "abc")
  | ($k | sub("[.]name"; ".url")) as $k
  | .[$k]
'

If you are looking for a general way to build a JSON array or object from such source, here's one way using reduce and setpath with regexes for splitting up the keys:如果您正在寻找从此类来源构建 JSON 数组或 object 的通用方法,这是一种使用reducesetpath以及正则表达式来拆分键的方法:

def build:
  reduce (to_entries[] | .key |= [
    splits("(?=\\[\\d+\\])|\\.")
    | capture("\\[(?<index>\\d+)\\]|(?<field>.+)")
    | (.index | tonumber)? // .field
  ]) as {$key, $value} (null; setpath($key; $value));

.servers | build.servers[] | select(.name == "abc").url

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM