0

I've below JSON, I want to parse all these key names product, inventory, rating, review dynamically and put it in the list and iterate the key name one by one.

{
    "product": [
        {
            "productID": "123",
            "productName": "test1"
        }
    ],
    "inventory": [
        {
            "id": "12093",
            "name": "adie"
        }
    ],
    "rating": [
        {
            "value": "4",
            "status": "done"
        }
    ],
    "review": [
        {
            "desc": "good",
            "comments": "test"
        }
    ]
}

After parsing the key name dynamically, I want to form all the key name in a comma separated and assigned to key_list variable like below:

key_list="product,inventory,rating,review"

After that I want to iterate key_list in a loop and print them or do something with that value. The desired output would be print the key name one by one in a loop:

product
inventory
rating
review

How can we achieve this using shell script jq?

4
  • Are you saying key_list is your output or your input? None of this is hard to do in jq (and it's all possible in jq alone -- no need to lean on the shell for any of the logic), but I'm not clear what your desired outcome is. Maybe show desired output, not just your inputs? (You want to iterate over the keys in the list and do what with them?) Commented Sep 17, 2022 at 21:25
  • It wouldn't hurt, also, to show what you tried. If you know how to feed your string into jq, and tried to split it on commas but something went wrong... well, knowing what went wrong would let us focus our answers on the specific thing you need to know. Commented Sep 17, 2022 at 21:28
  • Please follow the minimal reproducible example guidelines. Commented Sep 17, 2022 at 21:37
  • Updated the desired output Commented Sep 17, 2022 at 21:39

1 Answer 1

3

To produce a listing of the key names:

jq -r 'keys_unsorted[]'

To produce a comma-separated string with the key names, you could start with:

jq 'keys_unsorted|join(",")'
Sign up to request clarification or add additional context in comments.

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.