'Jolt Transform extracting data from flattened array into object
I am having some trouble with extracting data from a flattened array. I'm flattening a JSON file then using Jolt I am preparing the data.
Having this structure:
{
"body.places[0]_name": "Test",
"body.places[0]_population": "72",
"body.places[1]_name": "Demo",
"body.places[1]_population": "182"
}
I am trying to get to:
{
"place_test": "72"
"place_demo": "182"
}
Has anyone got any ideas on making this work?
Solution 1:[1]
With your unflattened input, this could have been a one-liner. Here, we have to unflatten it first.
jq '
to_entries
| reduce (
group_by((.key / "_")[0])[]
| map(.key |= (. / "_")[1])
| from_entries
) as $g (
{};
.["place_\($g.name | ascii_downcase)"] = $g.population
)
'
{
"place_test": "72",
"place_demo": "182"
}
Solution 2:[2]
Why not just:
{ place_test: .["body.places[0]_population"],
place_demo: .["body.places[1]_population"] }
Or if that trailing comma must be dealt with:
hjson -j | jq ...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pmf |
| Solution 2 | peak |
