简体   繁体   中英

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.

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.

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