Yogesh Jilhawar
Yogesh Jilhawar

Reputation: 6283

Not able to parse the json using jq

I have following json with me ( file name sample.json)-

{ "Prefix": "pg",
"fileFormat": "gz",
"additionalInfo": " {\"pgUsername\":\"postgres\",\"pgPassword\":\"postgres\",\"pgHostname\":\"pgmaster\"}"
}

I am reading these parameters using follwoing command-
cat sample.json | jq -r '.additionalInfo .pgPassword'

expected output is postgres, but I am getting something like [26]

I cant change this json. Does anyone knows, what command should be used to get correct output? Thanks in advance.

Upvotes: 1

Views: 925

Answers (2)

grundic
grundic

Reputation: 4921

Your json is incorrect (you can verify in on https://jsonlint.com), you can try this one:

{
    "additionalInfo": {
        "pgUsername": "postgres",
        "pgPassword": "postgres",
        "pgHostname": "pgmaster"
    }
}

And you will get expected result:

$ cat data.json| jq -r '.additionalInfo .pgPassword'
postgres

EDIT

For your modified data you can use:

$ cat data.json| jq -r '.additionalInfo' | jq '.pgPassword'
postgres

EDIT AGAIN

Please, see a comment by @peak -- it doesn't require multiple execution of jq, instead he proposes to use fromjson builtin.

Upvotes: 1

peak
peak

Reputation: 116640

Thanks to fromjson, there's no need to invoke jq twice:

jq -r '.additionalInfo|fromjson|.pgPassword' data.json
postgres

Upvotes: 2

Related Questions