简体   繁体   中英

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. Is there any way that i can get with JQ the url by searching for the name, like this?

{
    "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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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