divanov
divanov

Reputation: 6339

Convert JSON object to an array of strings with jq

I have a JSON object, which contains only strings and other objects:

{
  "key1": "value1",
  "key2": "value2",
  "key3": {
    "subKey1":"value3",
    "subKey2":"value4"
  }
}

I want to convert it to an array of strings by flattening the structure

[
  "key1.value1",
  "key2.value2",
  "key3.subKey1.value3",
  "key3.subKey2.value4",
]

I'm rather new to jq syntax and so far I managed to achieve only this with help of

to_entries | map([.key, .value | if type == "object" then type else . end]|join("."))

then I obtain

[
  "key1.value1",
  "key2.value2",
  "key3.object"
]

Upvotes: 2

Views: 625

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Short alternative:

jq '[paths(scalars) as $p | $p + [getpath($p)] | join(".")]' f.json

The expected output:

[
  "key1.value1",
  "key2.value2",
  "key3.subKey1.value3",
  "key3.subKey2.value4"
]

Upvotes: 2

peak
peak

Reputation: 116690

Using paths makes the task simple.

paths as $p
| getpath($p) 
| scalars
| $p + [.]
| join(".")

produces the stream:

"key1.value1"
"key2.value2"
"key3.subKey1.value3"
"key3.subKey2.value4"

So you'll want to enclose the filter above in square brackets to produce an array.

Upvotes: 1

Related Questions