ahmet alp balkan
ahmet alp balkan

Reputation: 45206

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 [???]

Upvotes: 1

Views: 3807

Answers (2)

yolenoyer
yolenoyer

Reputation: 9445

For those interested, here is a bash function which can create json dicts, by handling basic json types by adding a prefix to the bash values:

  • string (prefix: s:)
  • boolean (prefix: b:)
  • number (prefix: n:)

Here's the code:

#!/bin/bash

json_dict() {
    for s in "$@"; do
        echo -ne "$s\0"
    done \
    | jq  -R 'splits("\u0000")' \
    | jq -s -c '
        _nwise(2)
        | {
            (.[0]):
            (
                if .[1]|startswith("s:") then .[1][2:]
                elif .[1]|startswith("n:") then .[1][2:]|tonumber
                elif .[1] == "b:true" then true
                elif .[1] == "b:false" then false
                else .[1]
                end
            )
        }
    ' \
    | jq -s add
}

key_values=(
    k1 s:foo
    k2 b:true
    k3 n:123
)

json_dict "${key_values[@]}"

Output:

{
  "k1": "foo",
  "k2": true,
  "k3": 123
}

Upvotes: 0

peak
peak

Reputation: 116670

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"
}

Upvotes: 3

Related Questions