Mohit Kumar
Mohit Kumar

Reputation: 21

Convert a bash variable to JSON array and JSON object using jq

I have a variable, X, in a bash script that has a value like asw|uduu|sssdd. How can I convert it to a JSON array using jq?

A second variable, Y, has a value like A:1|B:1|C:1. How can I convert it to a JSON object using jq?

Please help me solve these conversion tasks.

Upvotes: 1

Views: 2069

Answers (1)

peak
peak

Reputation: 116730

echo 'asw|uduu|sssdd' | jq -Rc 'split("|")'

produces: ["asw","uduu","sssdd"]

The "-c" option is inessential here - it just compacts the output.

echo 'A:1|B:1|C:1' |
 jq -Rc 'split("|") | map( split(":") | {(.[0]): .[1]} ) | add'

produces: {"A":"1","B":"1","C":"1"}

To understand how the last one works, run the leftmost part of the pipeline first, and then add successive parts.

Upvotes: 1

Related Questions