Home > front end >  How to use jq to extract keys and print them a certain amount of times depending on another keys val
How to use jq to extract keys and print them a certain amount of times depending on another keys val

Time:09-11

So I'm trying to get the top-level keys and then multiply each one by the amount under each key then post the key as many times as the amount states.

How do I get jq to take json like this:

{
"2tMRnry9cMqcMo5JqPWvyFaznoU8ujcf3i9ALpzokFHK": {
    "mints": [
        "Ehmx5dGtUtYSTRYDNptYSPLXs4ZSFmCPHvPd5ProtGPp",
        "DZHynoX1yrwdppnNNZmBHqap89vziSehmhJP3BQESoaN",
        "CVdM8fu474xaVxxuUzLsn7rxTA1mcrkpq8K7YYN4gRoc"
    ],
    "amount": 3
},
"CVjVEB2WBmDACcovpxKAEqXZZKdUGsGAn2v5EsWSjtXX": {
    "mints": [
        "CPBsjXBKrG2QfRAkaPDJ282bXr7uD9259Ymb6EC93jjb"
    ],
    "amount": 1
},
"Cndq2Yjt1MVkQPYiZod9eGZcTHFDhuYjJA7N6vAuVw8H": {
    "mints": [
        "66T698sRaJiyEXu6RrBw8ApNYsx1spkQQZZM9nZdA9EE",
        "65QEUZVWMg12UvrRNcoV5DwVANKWaarHPd52KemV4pRy"
    ],
        "amount": 2
    }
}

and generate this output:

2tMRnry9cMqcMo5JqPWvyFaznoU8ujcf3i9ALpzokFHK
2tMRnry9cMqcMo5JqPWvyFaznoU8ujcf3i9ALpzokFHK
2tMRnry9cMqcMo5JqPWvyFaznoU8ujcf3i9ALpzokFHK
CVjVEB2WBmDACcovpxKAEqXZZKdUGsGAn2v5EsWSjtXX
Cndq2Yjt1MVkQPYiZod9eGZcTHFDhuYjJA7N6vAuVw8H
Cndq2Yjt1MVkQPYiZod9eGZcTHFDhuYjJA7N6vAuVw8H

CodePudding user response:

You can use to_entries to access key and value, and range to iterate:

jq -r 'to_entries[] | range(.value.amount) as $_ | .key'
2tMRnry9cMqcMo5JqPWvyFaznoU8ujcf3i9ALpzokFHK
2tMRnry9cMqcMo5JqPWvyFaznoU8ujcf3i9ALpzokFHK
2tMRnry9cMqcMo5JqPWvyFaznoU8ujcf3i9ALpzokFHK
CVjVEB2WBmDACcovpxKAEqXZZKdUGsGAn2v5EsWSjtXX
Cndq2Yjt1MVkQPYiZod9eGZcTHFDhuYjJA7N6vAuVw8H
Cndq2Yjt1MVkQPYiZod9eGZcTHFDhuYjJA7N6vAuVw8H

Demo

  • Related