a3y3
a3y3

Reputation: 1201

Add quotes only around strings, not numbers or lists

My input JSON is of the format:

{
  "a": "apple",
  "b": "banana",
  "c": 5,
  "d": ["this", "is", "an", "array"],
  "e": false
}

What I want is:

a="apple"
b="banana"
c=5
d=["this", "is", "an", "array"]
e=false

Note that only strings in the input JSON have quotes in the output.

By using jq -r 'to_entries[] | "\(.key)=\"\(.value)\""' I could generate an output like

a="apple"
b="banana"
c="5"
d="["this", "is", "an", "array"]"
e="false"

So my question is:

  1. Is using jq the right way to approach this problem? Or should I use regex?
  2. If jq is the correct direction, how do I fix what I've come up with?

Upvotes: 0

Views: 219

Answers (1)

user197693
user197693

Reputation: 2045

You can test whether .value is a string or not using type (manual entry).

jq -r 'to_entries[]
      | "\(.key) = \( .value 
                      | if type == "string"
                        then "\"\(.)\""
                        else . 
                        end
                    )"'

Upvotes: 2

Related Questions