Home > Mobile >  JQ pull value from key searched by related key
JQ pull value from key searched by related key

Time:03-18

Im bashing my head against a wall - aim pull value from key searched by related

JSON SNIPPIT

{
  "block": {
    "000545342981": [
      {
        "CODE": "xdxd3456532fok234sss0"
      },
      {
        "STATE": "COMPLETE"
      }
    ],
   "000545341211": [
      {
        "CODE": "xdff3678223frt244swe4"
      },
      {
        "STATE": "RUNNING"
      }
    ]
}}

I wish to retrieve the CODE value for each ACCOUNT

ie for 000545342981 i wish to have xdxd3456532fok234sss0 returned and xdff3678223frt244swe4 for 000545341211

then place in bash as

accounts =(
["000545342981"]=xdxd3456532fok234sss0
["000545341211"]=xdff3678223frt244swe4
)

SO FAR i have returned the accounts with jq --slurp '.?|.[][]|keys' | jq -r '.[]'

then i tried jq --arg code "ACCOUNT" 'select ( ."block".key==$code) | ."block".$stack."CODE"' ----> no errors :/ so suspect it may not of found anything

this will kind of work ."block"."000545341211"[]."CODE" but i know i cant input a var in jq from a for each so need arg input (unless im very wrong) its the select ( ."block".key==$code) i think?? what do i need :(

CodePudding user response:

If each account contains only one code, you can do :

#!/usr/bin/env bash

declare -A accounts
while read account code; do
    accounts[$account]=$code
done < <(jq -r '.block       |
                to_entries[] |
                "\(.key) \(.value[0].CODE)"' input.json)
declare -p accounts
  • Related