user8479984
user8479984

Reputation: 501

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

Upvotes: 2

Views: 69

Answers (2)

Inian
Inian

Reputation: 85550

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, i.e. ${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")"

Upvotes: 3

SiHa
SiHa

Reputation: 8411

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

Upvotes: 1

Related Questions