简体   繁体   中英

Using jq to create JSON objects/dictionaries

In my bash script I have a dictionary/map like:

k1: v1
k2: v2
k3: v3

Can I possibly use jq --slurp or jq --raw-input to actually convert this to JSON like this:

{
  "k1": "v1",
  "k2": "v2",
  "k3": "v3"
}

possibly by piping something like: echo k1 v1 k2 v2 k3 v3 | jq [???] echo k1 v1 k2 v2 k3 v3 | jq [???]

With the key: value data in input.txt, and the following program in tojson.jq:

[inputs | select(length>0) 
 | [splits(": *")]
 | {(.[0]): .[1]} ]
| add

the invocation:

jq -n -R -f tojson.jq input.txt

produces:

{
  "k1": "v1",
  "k2": "v2",
  "k3": "v3"
}

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