2

I'm totally brand new to JSON and jq so this might seem like a simple question. I'd like to change an array of numbers into an array of objects with a key for each value (number).

Let's say I have a JSON file like this:

{
"foo": [1519739200, 1519739600, 1519740000]
}

Then my desired output would be:

{
"foo": [
    {
       "id": 1519739200
    },
    {
       "id": 1519739600
    },
    {
       "id": 1519740000
    },
  ]
}

So far everything I've seen was connected with adding new keys with values to existing object or merging two arrays into few objects. I know that I can add more keys into already existing object but how can I add keys to an array? I assume I have to change array elements into objects first but how do I do it? Thank you for answer.

2 Answers 2

2

Check this,

https://jqplay.org/s/xF9DyVbhXD

{ foo : [ { id : .foo[] } ] }
Sign up to request clarification or add additional context in comments.

Comments

0

There are a few ways to go about it.

First you want to create a new object for each item in foo:

$ jq -c '{ id: .foo[] }'
{"id":1519739200}
{"id":1519739600}
{"id":1519740000}

You can then rebuild the "shape" you had - first with [ ... ]

$ jq -c '[ { id: .foo[] } ]' 
[{"id":1519739200},{"id":1519739600},{"id":1519740000}]

Then the { foo: }

$ jq -c '{ foo: [ { id: .foo[] } ] }' 
{"foo":[{"id":1519739200},{"id":1519739600},{"id":1519740000}]}

Another option is to use |= to modify/update .foo directly.

$ jq -c '.foo |= [{id: .[]}]' 
{"foo":[{"id":1519739200},{"id":1519739600},{"id":1519740000}]}

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.