user7701939
user7701939

Reputation:

jq create a new json by transforming an existing one

    {
    "prodid_876006": {
        "serid": [{
            "seridone": "3265874"
        }, {
            "seridtwo": "21458915"
        }],
        "serials": ["028915"]
    },
    "prodid_980": {
        "serid": [{
            "seridone": "32743214"
        }, {
            "seridtwo": "5469872"
        }],
        "serials": ["192147","1632589"]
    }
}

desired output: for each json object, extract the prodid_ info, and the serials array, and make a new json file, with the following format:

{    
"prodid_876006" : ["028915"],
"prodid_980" : ["192147","1632589"]
}

what would be the jq command for this?

keys ,.[].serials

gives me the following:

[
  "prodid_876006",
  "prodid_980"
]
[
  "028915"
]
[
  "192147",
  "1632589"
]

updated question:

how could i also get in another json the following output? (here the key is each element of the serials array, and the value is the key of the first sample json):

{    
"028915" : ["prodid_876006"],
"192147" : ["prodid_980"],
"1632589" : ["prodid_980"]
}

Upvotes: 1

Views: 1392

Answers (2)

knittl
knittl

Reputation: 265928

For question #1, simply replace the value by the serials property:

with_entries(.value|=.serials)

Output:

{
  "prodid_876006": [
    "028915"
  ],
  "prodid_980": [
    "192147",
    "1632589"
  ]
}

For your second question, see this answer to an almost identical question. You can combine the solution from the linked answer with the solution for question #1:

with_entries(.value|=.serials)
| with_entries({key:.value[], value:[.key]})

or do it in a single step:

with_entries({key:.value.serials[], value:[.key]})

In both cases, the output will be:

{
  "028915": [
    "prodid_876006"
  ],
  "192147": [
    "prodid_980"
  ],
  "1632589": [
    "prodid_980"
  ]
}

Upvotes: 0

johnsyweb
johnsyweb

Reputation: 141998

Something like this will work, where you extract an array of key-value pairs and pipe to from_entries:

% jq '[to_entries[] | {"key": .key, "value": .value.serials}] | from_entries' 42762941.json
{
  "prodid_876006": [
    "028915"
  ],
  "prodid_980": [
    "192147",
    "1632589"
  ]
}

Upvotes: 2

Related Questions