2

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

2 Answers 2

2

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"
]
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.