简体   繁体   中英

Accessing JSON value via jq using variable key

I have a file with JSON like: test.json

{
    "NUTS|/nuts/2010": {
        "type": "small",
        "mfg": "TSQQ",
        "colors": []
    }
}

I am getting "NUTS|/nuts/2010" from outside and I am storing it in a shell variable. I am trying to use the below snippet and using jq util, but I am not able to access the corresponding json against the above key.

test.sh

#!/bin/bash

NUTS_PATH="NUTS|/nuts/2010" #Storing in shell variable
INPUT_FILE="test.json"
RESULT=($(jq -r --arg NUTS_PATH_ALIAS "$NUTS_PATH" '.[$NUTS_PATH_ALIAS]' $INPUT_FILE))

echo "Result: $RESULT"
echo $RESULT > item.json

When I run this, I am getting:

Result: {

But it should return

{
        "type": "small",
        "mfg": "TSQQ",
        "colors": []
    }

Any help. Thanks

The problem isn't associated with jq at all. What you have should work fine, but the issue is with the assignment of the result to an array when you might have intended to store it in a variable

RESULT=($(jq -r --arg NUTS_PATH_ALIAS "$NUTS_PATH" '.[$NUTS_PATH_ALIAS]' $INPUT_FILE))
#     ^^^ =( .. ) result is stored into an array

A variable like expansion of an array of form $RESULT refers to element at index 0, ie ${RESULT[0]} , which contains the { character of the raw JSON output

You should ideally be doing

RESULT="$(jq -r --arg NUTS_PATH_ALIAS "$NUTS_PATH" '.[$NUTS_PATH_ALIAS]' "$INPUT_FILE")"

I always end up swearing at jq, too!

For me, this jq query works:

$ jq '.["NUTS|/nuts/2010"]' test.json
{
  "type": "small",
  "mfg": "TSQQ",
  "colors": []
}

However, because you've got pipes and slashes in your string, the variable quoting gets a bit funny.

NUTS_PATH='"NUTS|/nuts/2010"' #Note the two sets of quotes
INPUT_FILE="test.json"
RESULT=$(jq ".[$NUTS_PATH]" $INPUT_FILE)

echo "Result: $RESULT"

Result: {
  "type": "small",
  "mfg": "TSQQ",
  "colors": []
}

Disclaimer, I'm not a BASH expert, there may (probably is) be a better way to sort out the quoting

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